Bubble sort is one of the many sorting algorithms that people use to sort a list.
Worst case performance- O(n^2)
Best case performance- O(n): ironically this only happens if the list is already sorted
Example source code:
void bubbleSort(int numbers[], int array_size)
{
int i, j, temp;
int sorted=1;
for (i = (array_size - 1); i >= 0; i--)
{
sorted=1;
for (j = 1; j <= i; j++)
{
if (numbers[j-1] > numbers[j])
{
temp = numbers[j-1];
numbers[j-1] = numbers[j];
numbers[j] = temp;
sorted=0;
}
}
if (sorted) { break; } //if done in first loop this it makes best case performance
}
}
Example of the first loop: array: [45, 67, 12, 34, 25, 39]
In the first step, the focus is on the first two elements which are compared and swapped, if necessary. In this case, since the element at index 1 is larger than the one at index 0, no swap takes place.
45, 67, 12, 34, 25, 39
Then the focus move to the elements at index 1 and 2 which are compared and swapped, if necessary. In this example, 67 is larger than 12 so the two elements are swapped. The result is that the largest of the first three elements is now at index 2.
45, 12, 67, 34, 25, 39
The process is repeated until the focus moves to the end of the array, at which point the largest of all the elements ends up at the highest possible index. The remaining steps result are:
45, 12, 34, 67, 25, 39
45, 12, 34, 25, 67, 39
45, 12, 34, 25, 39, 67
Then repeat the same process starting at index 0;
For more detail here: Bubble Sort