Bubble sort sorts the elements of the array by comparing every element with the previous element.
Here is the high level overview for implementing bubble sorting algorithm.
We use two loops :inner and outer.
1.Outer loop:Loop from first element to last element
2.Inner loop:Loop from the last element to the current item
3. In every iteration of inner loop:Compare the current item to the previous item.If the current item is less than the previous item then swap the items.
for example if there are 5 items in a array.here you will use two loops.
- In the outer loop you will iterate from first element to last element.This is the current item.So you will iterate from the first index 0 to index 4.
- In the inner loop you will iterate from the last element to the current item.So you will iterate from index 4 to 0,1,2,3.
In this case the total number of comparisons will be:
For the first iteration of outer loop there will be 4 comparisons.
- In the second iteration there will be 3 com prisons since you will loop from 3 to 0 index.
- In the third iteration there will be 2 comparisons since you will loop from 2 to 0 index.
- In the fourth iteration there will be 1 comparisons since you will loop from 1 to 0 index.
You can add the above values for total number of comparions.So total number of comparions is 10 here.
this can be expressed using the simple formula:
(n-1) + (n-2) + (n-3) …(2) + (1) = n(n – 1)/2
If you put n=5 here then it should come as already validated above.
So if you put n=5 then:
5(5-1)/2= 5(4)/2=20/2=10
So using this fromula we get the same value 10 as we have validated above.
We can express bubble sort in C# as:
int[] intArray = { 20,2, 4, 6, 7, 18, 2, 1, 3 }; for (int i = 0; i < intArray.Length; i++) { for (int j = intArray.Length - 1; j > i; j--) { if (intArray[j] < intArray[j - 1]) { var temp = intArray[j]; intArray[j] = intArray[j - 1]; intArray[j - 1] = temp; } } Console.WriteLine("\n"); Console.WriteLine("pass={0}", i); foreach (var item in intArray) { Console.WriteLine("x={0}", item); } } Console.ReadLine();
Leave a Reply