Sorting a list is one of the most studied operations in programming. Python does it for you with sort() and sorted(), but understanding how to sort by hand teaches you to reason with loops and lists.
Sorting with Python
l = [7, 2, 5, 1]
l.sort()
print(l) # [1, 2, 5, 7]
print(sorted(l, reverse=True)) # [7, 5, 2, 1]
Swapping two elements
The basic piece of many sorting algorithms is swapping two positions. In Python it is done without an auxiliary variable:
l = [7, 2, 5]
l[0], l[1] = l[1], l[0]
print(l) # [2, 7, 5]
Bubble sort
You go through the list comparing each element with the next one. If they are in the wrong order, they are swapped. With each complete pass, the largest of those left "rises" like a bubble to its final position.
Example with [4, 3, 1, 2]:
| Pass | State of the list | What happens |
|---|---|---|
| 1 | [3, 4, 1, 2], [3, 1, 4, 2], [3, 1, 2, 4] | the 4 rises to the end |
| 2 | [1, 3, 2, 4], [1, 2, 3, 4] | the 3 stays in place |
| 3 | [1, 2, 3, 4] | it is already sorted |
The algorithm in Python
l = [4, 3, 1, 2]
n = len(l)
for i in range(n - 1): # n - 1 passes
for j in range(n - 1 - i): # the unsorted zone shrinks
if l[j] > l[j + 1]:
l[j], l[j + 1] = l[j + 1], l[j]
print(l) # [1, 2, 3, 4]
Notice n - 1 - i: after each pass, the last i elements are already in place, so there is no need to look at them again. It also prevents l[j + 1] from going out of the list.
It is the basis of Bubble sort, where you are asked to implement the algorithm by hand without using sort().
Why does it matter?
Bubble sort is simple but slow: for n elements it makes about n × n comparisons. With 10 numbers you do not notice; with a million, you do. That is why Python internally uses a much faster algorithm.