Bubble Sort In C#

Bubble Sort is a sorting algorithm (an algorithm that puts elements of a list in a certain order). The simplest sorting algorithm is Bubble Sort. In the Bubble Sort, as elements are sorted they gradually "bubble up" to their proper location in the array, like bubbles rising in a glass of soda.

The Bubble Sort works by iterating down an array to be sorted from the first element to the last, comparing each pair of elements and switching their positions if necessary. This process is repeated as many times as necessary, until the array is sorted.

Bubble Sort In C#

When this first pass through the array is complete, the Bubble Sort returns to elements one and two and starts the process all over again. The Bubble Sort has stopped when it is finished examining the entire array and no "swaps" are needed.

To sort an array there will be n-1 passes where n is the number of elements in the array. In the above diagram there are seven elements in an array so there will be 7-1=6 passes.

Bubble Sort In C#

Bubble Sort Algorithm

Procedure BubbleSort(DATA : list of sortable items)

N= DATA.Length

  1. Set Flag := True
  2. Repeat Steps from 3 to 5 for I = 1 to N-1 while Flag == true
  3. Set Flag := False
  4. Set J:=0. [Initialize pass pointer J]
  5. Repeat while J<N-1 [Executes pass]

    (a) If DATA[J+1]>DATA[J], then:
    Swap DATA[J] and DATA[J+1]
    Set Flag:= True
    [End of If structure]

    (b) Set J:=J+1
    [End of inner loop]
    [End of step 1 outer loop]

  6. Exit

Bubble Sort in C#

using System;  
namespace SortingExample  
    class Program  
        static void Main(string[] args)  
            int[] number = { 89, 76, 45, 92, 67, 12, 99 };  
            bool flag = true;  
            int temp;  
            int numLength = number.Length;  
            //sorting an array  
            for (int i = 1; (i <= (numLength - 1)) && flag; i++)  
                flag = false;  
                for (int j = 0; j < (numLength - 1); j++)  
                    if (number[j + 1] > number[j])  
                        temp = number[j];  
                        number[j] = number[j + 1];  
                        number[j + 1] = temp;  
                        flag = true;  
            //Sorted array  
            foreach (int num in number)  
                Console.Write("\t {0}",num);  


Bubble Sort In C#

Similar Articles