Bubble Sort Algorithm 03-14-2014, 06:33 PM
#1
I felt like writing a sorting algorithm, so i present to you the bubble sort algorithm:
Code:
// Bubble Sort
bool bDone = false; // this flag will be used to check whether we have to continue the algorithm
printArray(array, size, "-"); // print the initial array
while (!bDone)
{
bDone = true; // assume that the array is currently sorted
for (int i = 0; i != size - 1; ++i) // for every element in the array
{
if ( array[i] > array[i + 1] ) // compare the current element with the following one
{
// They are in the wrong order, swap them
T tmp = array[i];
array[i] = array[i+1];
array[i+1] = tmp;
bDone = false; // since we performed a swap, the array needs to be checked to see if it is sorted
// this is done in the next iteration of the while
printArray(array, size, "-"); // print current array to show the steps done by the algorithm
}
}
}
printArray(array, size, "-"); // print final array
![[+]](https://sinister.li/images/modern/collapse_collapsed.png)
![[Image: OilyCostlyEwe.gif]](http://fat.gfycat.com/OilyCostlyEwe.gif)


![[Image: 2YpkRjy.png]](http://i.imgur.com/2YpkRjy.png)