Classic algorithms · 5 / 22 Theory

Divide and conquer: merge sort and quicksort

The bubble, selection and insertion sorting algorithms take a time proportional to n²: with 100,000 elements that is billions of steps. The two algorithms in this article drop to n log n with a recursive idea: divide and conquer.

Merge sort

The list is split into two halves, each half is sorted recursively and the two sorted halves are merged. The merge is the key part: with two sorted lists it is enough to always look at the first remaining elements and take the smaller one.

def merge(a, b):
    result = []
    i = j = 0
    while i < len(a) and j < len(b):
        if a[i] <= b[j]:
            result.append(a[i]); i += 1
        else:
            result.append(b[j]); j += 1
    return result + a[i:] + b[j:]

def sort_list(items):
    if len(items) <= 1:
        return items
    half = len(items) // 2
    return merge(sort_list(items[:half]), sort_list(items[half:]))

print(merge([1, 4, 6], [2, 3, 7]))     # [1, 2, 3, 4, 6, 7]
print(sort_list([5, 2, 4, 7, 1, 3]))       # [1, 2, 3, 4, 5, 7]

Since each division level processes n elements and there are log n levels, the cost is always O(n log n), in exchange for using extra memory for the intermediate lists. You implement it counting comparisons in Merge sort.

Quicksort

A pivot is chosen, the other elements are distributed into smaller and larger than it, and each group is sorted recursively. It needs no merge phase: when concatenating smaller + equal + larger it is already sorted.

def quicksort(items):
    if len(items) <= 1:
        return items
    pivot = items[0]
    smaller = [x for x in items if x < pivot]
    equal = [x for x in items if x == pivot]
    larger = [x for x in items if x > pivot]
    return quicksort(smaller) + equal + quicksort(larger)

print(quicksort([5, 2, 4, 7, 1, 3, 4]))     # [1, 2, 3, 4, 4, 5, 7]

On average it takes O(n log n), but if the pivot is always the smallest or the largest (for example, in a list that already comes sorted and with the pivot as the first element) the groups become very uneven and it degenerates to O(n²). In practice the pivot is chosen at random or as the median of three values. You practice it, counting the calls, in Quicksort.

Comparison

AlgorithmBest caseAverage caseWorst caseExtra memory
Bubble / selection / insertionO(n) or O(n²)O(n²)O(n²)O(1)
Merge sortO(n log n)O(n log n)O(n log n)O(n)
QuicksortO(n log n)O(n log n)O(n²)O(log n) of stack
Counting sortO(n + k)O(n + k)O(n + k)O(k)

Python uses sorted() and list.sort() with Timsort, a hybrid of merge and insertion, stable and O(n log n). In real code you almost never write your own sort; studying them helps to understand the cost of things.

Stability

An algorithm is stable if it keeps the relative order of equal elements. Merge (with <=) and insertion are; selection and the simple quicksort are not necessarily. It matters when sorting by several criteria.