Classic algorithms · 2 / 22 Theory

Sorting algorithms

Sorting is another classic problem. Python already includes sorted() and list.sort(), but knowing the basic algorithms teaches you to think step by step. The following three are simple and share an idea: comparing and swapping elements.

Bubble sort

It goes through the list comparing each element with the next one; if they are the wrong way round, it swaps them. After each pass, the largest one "bubbles up" to the end. It repeats until a pass changes nothing:

numbers = [5, 1, 4, 2, 8]

while True:
    swapped = False
    for i in range(len(numbers) - 1):
        if numbers[i] > numbers[i + 1]:
            numbers[i], numbers[i + 1] = numbers[i + 1], numbers[i]
            swapped = True
    if not swapped:
        break

print(numbers)  # [1, 2, 4, 5, 8]

items[i], items[j] = items[j], items[i] swaps two elements without needing an auxiliary variable.

Selection sort

At each step it looks for the smallest of the elements that are still unsorted and puts it in its place:

numbers = [64, 25, 12, 22, 11]

for i in range(len(numbers) - 1):
    pos_min = i
    for j in range(i + 1, len(numbers)):
        if numbers[j] < numbers[pos_min]:
            pos_min = j
    numbers[i], numbers[pos_min] = numbers[pos_min], numbers[i]

print(numbers)  # [11, 12, 22, 25, 64]

Insertion sort

It is like sorting cards in your hand: you take the next card and insert it in its place among the ones already sorted, shifting the larger ones to the right:

numbers = [12, 11, 13, 5, 6]

for i in range(1, len(numbers)):
    key = numbers[i]
    j = i - 1
    while j >= 0 and numbers[j] > key:
        numbers[j + 1] = numbers[j]
        j -= 1
    numbers[j + 1] = key

print(numbers)  # [5, 6, 11, 12, 13]

Comparison

AlgorithmIdeaIf the list is already sorted
BubbleSwap neighbours that are out of orderA single pass, very fast
SelectionFind the smallest and place itDoes the same work anyway
InsertionInsert each element in its placeHardly does anything, very fast

All three need about n² comparisons in the worst case: if you double the size of the list, they take four times longer. For large lists, Python uses more advanced algorithms (sorted uses *Timsort*).

numbers = [5, 1, 4, 2, 8]

print(sorted(numbers))                # [1, 2, 4, 5, 8]
print(sorted(numbers, reverse=True))  # [8, 5, 4, 2, 1]

Practice with Bubble sort, Selection sort and Insertion sort.