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, but it is not adaptive.

=Explanation= Bubble sort makes $$n$$ passes through the array, exchanging consecutive elements if they are in the wrong order. For example:

4 3 5 2 1

first, consider elements at index 0 and 1. they are out of order, so swap them.

3 4 5 2 1

consider elements at index 1 and 2. they are in order, so leave them.

3 4 5 2 1

consider elements at index 2 and 3. they are out of order, so swap them.

3 4 2 5 1

consider elements at index 3 and 4. they are out of order, so swap them.

repeat.

3 4 2 1 5

compare 0 and 1

3 4 2 1 5

compare 1 and 2, swap

3 2 4 1 5

compare 2 and 3, swap

3 2 1 4 5

compare 0 and 1, swap

2 3 1 4 5

compare 1 and 2, swap

2 1 3 4 5

compare 0 and 1, swap

1 2 3 4 5

Sorted!

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