Bubble Sort

Bubble sort is an $$O(n^2)$$ algorithm for sorting arrays with $$O(1)$$ memory. it works by "bubbling" each element up to the top. It is stable and adaptive.

Algorithm
Bubble sort makes $$n$$ passes rightward through the array, exchanging consecutive elements if they are in the wrong order. It will also stop when no swaps are made, meaning the array is sorted.

Example
Bubble sorting a list of 5 elements:

[5 3 4 1 2] └─┘

Compare and swap.

[3 5 4 1 2]   └─┘

Keep comparing until you reach the end of the list.

[3 4 5 1 2]     └─┘ [3 4 1 5 2]        └─┘ [3 4 1 2 5]

Repeat until n passes are made or the array is sorted.

[3 1 2 4 5] [1 2 3 4 5]

Pseudocode
procedure bubble_sort(array arr) do do swapped = false for i = 0 to length(arr-1) do if arr[i] > arr[i + 1] do swap arr[i] and arr[i + 1] swapped = true end if end for while swapped end

Optimizations
It can be observed that for each pass in the array, the largest element will be always at the end of the array. Then the second to the largest, and so on. The new code is as follows:

procedure bubble_sort(array arr) do n = length(arr-1) do swapped = false for i = 0 to n do if arr[i] > arr[i + 1] do swap arr[i] and arr[i + 1] swapped = true end if end for n = n - 1 while swapped end

Furthermore, elements after the last swap are also considered sorted, which means multiple elements are done. The  variable is replaced:

procedure bubble_sort(array arr) do n = length(arr-1) do lastSwap = 0 for i = 0 to n do if arr[i] > arr[i + 1] do swap arr[i] and arr[i + 1] lastSwap = i         end if end for while lastSwap > 0 end

Slight variations of the algorithm may be also used, such as cocktail shaker sort.

Cocktail Shaker Sort
Also called bidirectional bubble sort, this improves upon bubble sort by moving in two directions, going rightward and leftward each time until the list is sorted.