In bubble sort, we place last n-1
numbers at their correct place one by one, starting from index n-1
till index 1
. So, n-1
iterations are required i.e. for i
in range n-1..1
.
Example
list = [5, 4, 3, 2, 1]
size = 5
iterations required = 4 (from 4 to 1)
i=4 : 4th index is correctly set : [4, 3, 2, 1, 5]
i=3 : 3rd index is correctly set : [3, 2, 1, 4, 5]
i=2 : 2nd index is correctly set : [2, 1, 3, 4, 5]
i=1 : 1st index is correctly set : [1, 2, 3, 4, 5]
If we imagine start of list as bottom and end of list as top of a water container, then bubble sort algorithm makes larger numbers bubble up to their correct positions. In the above example,
- On iteration
i=4
, largest number5
bubbles up to its correct position index4
- On iteration
i=3
, second largest number4
bubbles up to its correct position index3
- On iteration
i=2
, third largest number3
bubbles up to its correct position index2
- On iteration
i=1
, fourth largest number2
bubbles up to its correct position index1
Bubbling up n-1
numbers to their correct positions works but how do we perform this algorithmically? We can do so using consecutive swaps. To make a number bubble up to its to its correct position i
, we have to perform i
comparisons. Firstly positions 0
& 1
are compared, then positions 1
& 2
, till the positions i-1
& i
i.e. we compare positions j
& j+1
for j
in range 0..i-1
. On each comparison if larger number is found before a smaller number i.e. list[j] > list[j+1]
, we swap the positions.
Example
list = [5, 4, 3, 2, 1]
i in 4..1
iteration i=4 :
j in 0..i-1 = 0..3
j=0 : list[0] > list[1] : 5 > 4 : true, swap : [4, 5, 3, 2, 1]
j=1 : list[1] > list[2] : 5 > 3 : true, swap : [4, 3, 5, 2, 1]
j=2 : list[2] > list[3] : 5 > 2 : true, swap : [4, 3, 2, 5, 1]
j=3 : list[3] > list[4] : 5 > 1 : true, swap : [4, 3, 2, 1, 5]
5 bubbles up to its correct position i=4
iteration i=3 :
j in 0..i-1 = 0..2
j=0 : list[0] > list[1] : 4 > 3 : true, swap : [3, 4, 2, 1, 5]
j=1 : list[1] > list[2] : 4 > 2 : true, swap : [3, 2, 4, 1, 5]
j=2 : list[2] > list[3] : 4 > 1 : true, swap : [3, 2, 1, 4, 5]
4 bubbles up to its correct position i=3
Similarly,
after i=2, 3 bubbles up to its correct position i=2 :
[2, 1, 3, 4, 5]
after i=1, 2 bubbles up to its correct position i=1 :
[1, 2, 3, 4, 5]
Array is sorted!
To summarize, we need two nested loops (one inside another) :
- Outer loop will be of
i
in rangen-1..1
(orlastIndex downTo 1
) - Inner loop will be of
j
in range0..i-1
(or0 until i
)