Pages

Friday, November 29, 2013

C#: Bubble Sort

Bubble sorting is the simplest sorting algorithm. In bubble sort, we compare the consecutive pair of values in an array. Start from the beginning of the array, compare the first value with the following next value. If the first value is greater than the following value, then swap both the values. Else continue with the next consecutive pair. Continue this process for n-1 times, where n is the length of an array.

Suppose, you have an unsorted array of 5 elements
    
                             
 Here first iteration compare the first value with the second value









Now continue the iteration 4 times ie, n-1 times where n is the number of elements in an array
After 4 iterations the array will be as follows,



It's very easy to implement the above algorithm not only using C# but also in every programing languages. Here's an example program

//Method for bubble sorting
public void bubble(List<int> sort)
        {
//set a temporary variable
            int tempvar;
//Iterate through n-1 times
            for (int i = 1; i <= sort.Count; i++)
            {
//loop through each elements in all iterations
                for (int j = 0; j < sort.Count-i; j++)
                {
//compare each value with the following value,
//if greater then swap, else continue to next consecutive pair
                    if (sort[j] > sort[j + 1])
                    {
                        tempvar = sort[j];
                        sort[j] = sort[j + 1];
                        sort[j + 1] = tempvar;
                    }
                }
            }
//display sort
            display(sort);
        }

//Input array: {3,2,4,1,5}

Output:
1,2,3,4,5

No comments:

Post a Comment