Sorting algorithm: Bubble-Sort

Bubble-Sort is an easy to understand, but mostly inefficient (time complexity O(n2)) approach to sorting values of a list by order of magnitude.

It is rarely used in practice, at most in niche applications (e.g. embedded systems) or for academic purposes, due to its simplicity.

Nevertheless, under certain circumstances it performs better than other sorting algorithms, namely with almost completely sorted data sets.

It is not generally to be discouraged, for small data sets it is acceptable in terms of speed, which makes it suitable for simple scenarios.

Process

Enough beating around the bush, how does the algorithm work?

A so-called ‘cursor’ is set at one end of the list to be sorted, typically on the left.
This jumps from one value to the next.
Before each jump of this cursor, the current value is compared with the neighbouring value.
If this is smaller than the current value, they are swapped.
If the cursor reaches the end, the process is repeated from the 1st entry, provided swaps have taken place in that pass.

That was the purest form of bubble sort. A common optimised version is to shorten the list by the last entry after each pass. As this entry is guaranteed to be in the correct position after a complete run, further comparisons with it no longer need to be carried out.

The name bubblesort takes its inspiration from the bubble-like “rising” of the largest values to the top.

Example

As Code

The following lines of code illustrate bubblesort in JavaScript:

function bubbleSort(list) {
    for (let pendingListItems = list.length; pendingListItems > 0; pendingListItems--) {
        for (let listIndex = 0; listIndex < pendingListItems - 1; listIndex++) {
            if (list[listIndex] > list[listIndex + 1]) {
                const tempItem = list[listIndex];
                list[listIndex] = list[listIndex + 1];
                list[listIndex + 1] = tempItem;
            }
        }
    }
    return list;
}