C# Program to Implement Bubble Sort
Posted by Superadmin on August 15 2022 09:36:44

C# Program to Implement Bubble Sort

 

 

This is a C# Program to perform bubble sort.

Problem Description

This C# Program Performs Bubble Sort.

Problem Solution

Here bubble sort changes the position of numbers or changing an unordered sequence into an ordered sequence.

Program/Source Code

Here is source code of the C# Program to Perform Bubble Sort. The C# program is successfully compiled and executed with Microsoft Visual Studio. The program output is also shown below.

/*
 * C# Program to Perform Bubble Sort
 */
using System;
class bubblesort
{
        static void Main(string[] args)
        {
            int[] a = { 3, 2, 5, 4, 1 };  
            int t;
            Console.WriteLine("The Array is : ");
            for (int i = 0; i < a.Length; i++)
            {
                Console.WriteLine(a[i]);
            }
            for (int j = 0; j <= a.Length - 2; j++)
            {
                for (int i = 0; i <= a.Length - 2; i++)
                {
                    if (a[i] > a[i + 1])
                    {
                        t = a[i + 1];
                        a[i + 1] = a[i];
                        a[i] = t;
                    }
                }
            }
            Console.WriteLine("The Sorted Array :");
            foreach (int aray in a)                         
                Console.Write(aray + " ");
            Console.ReadLine();
        }
    }
Program Explanation

This C# Program is used to perform bubble sort. Using for loop we have already defined the value of ‘a[]’ variable. Here bubble sort changes the position of numbers or changing an unordered sequence into an ordered sequence.

 

If condition statement is used to check that the value in ‘present’ variable is greater than the value in ‘next’ variable. If the condition is true then execute the statement. Interchange the value using temporary variable‘t’ and print the bubble sort values.

Runtime Test Cases
 
The Array is :
3
2
5
4
1
The Sorted Array :
1
2
3
4
5