TExcelTAD
Home › Data Structures & Algorithms › Simple Sorts: Complexity

Simple Sorts: Complexity

Bubble sort, selection sort and insertion sort are all O(n²) in the worst case, but they behave quite differently on real inputs. In this lesson we count their operations exactly and see where the formulas come from.

Where n² comes from

All three use two nested loops. The inner loop runs over a shrinking (or growing) part of the array, so the total number of comparisons in the worst case is

text
(n - 1) + (n - 2) + ... + 2 + 1  =  n(n - 1) / 2

That is about n²/2, which is O(n²). For 10 values it's 45 comparisons, for 1,000 values almost half a million.

Counting all three

python · try it yourself
def bubble(a):
    a, comps, swaps = list(a), 0, 0
    for p in range(len(a) - 1):
        swapped = False
        for j in range(len(a) - 1 - p):
            comps += 1
            if a[j] > a[j + 1]:
                a[j], a[j + 1] = a[j + 1], a[j]
                swaps += 1
                swapped = True
        if not swapped:
            break
    return comps, swaps

def selection(a):
    a, comps, swaps = list(a), 0, 0
    for i in range(len(a) - 1):
        m = i
        for j in range(i + 1, len(a)):
            comps += 1
            if a[j] < a[m]:
                m = j
        if m != i:
            a[i], a[m] = a[m], a[i]
            swaps += 1
    return comps, swaps

def insertion(a):
    a, comps, moves = list(a), 0, 0
    for i in range(1, len(a)):
        key, j = a[i], i - 1
        while j >= 0:
            comps += 1
            if a[j] <= key:
                break
            a[j + 1] = a[j]
            moves += 1
            j -= 1
        a[j + 1] = key
    return comps, moves

n = 100
inputs = {
    "sorted": list(range(n)),
    "reversed": list(range(n, 0, -1)),
    "scrambled": [(k * 37) % n for k in range(n)],
}
print(f"n = {n}, n(n-1)/2 = {n * (n - 1) // 2}")
print(f"{'input':>10} | {'bubble':>13} | {'selection':>13} | {'insertion':>13}")
print(f"{'':>10} | {'comps  swaps':>13} | {'comps  swaps':>13} | {'comps  moves':>13}")
for name, data in inputs.items():
    row = [f"{c:>5} {s:>6}" for c, s in (bubble(data), selection(data), insertion(data))]
    print(f"{name:>10} | " + " | ".join(f"{r:>13}" for r in row))
n = 100, n(n-1)/2 = 4950
     input |        bubble |     selection |     insertion
           |  comps  swaps |  comps  swaps |  comps  moves
    sorted |     99      0 |   4950      0 |     99      0
  reversed |   4950   4950 |   4950     50 |   4950   4950
 scrambled |   4895   2448 |   4950     88 |   2547   2448

What the table shows:

  • Selection sort always makes exactly n(n-1)/2 = 4950 comparisons, whatever the input, but never more than n - 1 swaps.
  • Bubble sort (with the early exit) and insertion sort need only n - 1 = 99 comparisons on sorted input: they are adaptive.
  • On reversed input, bubble sort and insertion sort both hit the maximum of 4950 comparisons and 4950 swaps/moves.

The worst case, animated

Reversed input is the worst case for insertion sort: every new value must travel all the way to the front. Count the "shift left" steps: 1 + 2 + 3 + 4 + 5 = 15 = 6·5/2.

python · try it yourself
def insertion_shifts(a):
    a, shifts = list(a), 0
    for i in range(1, len(a)):
        j = i
        while j > 0 and a[j - 1] > a[j]:
            a[j - 1], a[j] = a[j], a[j - 1]
            shifts += 1
            j -= 1
        print(f"after inserting index {i}: {a}  (shifts so far: {shifts})")
    return shifts

print("total:", insertion_shifts([6, 5, 4, 3, 2, 1]))
after inserting index 1: [5, 6, 4, 3, 2, 1]  (shifts so far: 1)
after inserting index 2: [4, 5, 6, 3, 2, 1]  (shifts so far: 3)
after inserting index 3: [3, 4, 5, 6, 2, 1]  (shifts so far: 6)
after inserting index 4: [2, 3, 4, 5, 6, 1]  (shifts so far: 10)
after inserting index 5: [1, 2, 3, 4, 5, 6]  (shifts so far: 15)
total: 15

Doubling experiments

A practical way to check a complexity class: double n and see what happens to the operation count. Linear work doubles; quadratic work quadruples.

python · try it yourself
def selection_comparisons(n):
    return n * (n - 1) // 2          # same for every input

def insertion_comparisons_reversed(n):
    a, comps = list(range(n, 0, -1)), 0
    for i in range(1, n):
        key, j = a[i], i - 1
        while j >= 0:
            comps += 1
            if a[j] <= key:
                break
            a[j + 1] = a[j]
            j -= 1
        a[j + 1] = key
    return comps

previous = None
for n in [100, 200, 400, 800]:
    c = insertion_comparisons_reversed(n)
    growth = f"x{c / previous:.2f}" if previous else ""
    print(f"n={n:>4}: {c:>6} comparisons {growth}")
    previous = c
n= 100:   4950 comparisons
n= 200:  19900 comparisons x4.02
n= 400:  79800 comparisons x4.01
n= 800: 319600 comparisons x4.01

Each doubling multiplies the work by almost exactly 4: the signature of O(n²).

Summary

Best Average Worst Swaps / writes (worst) Stable Adaptive
Bubble sort O(n) O(n²) O(n²) O(n²) yes yes (early exit)
Selection sort O(n²) O(n²) O(n²) O(n) no no
Insertion sort O(n) O(n²) O(n²) O(n²) yes yes

All three use O(1) extra memory. In practice, insertion sort is the best of the three: it is simple, stable, fast on nearly sorted data, and has very little overhead, which is why fast library sorts switch to it for small pieces.

Test yourself

How many comparisons does selection sort make on 20 values?

  1. 19
  2. 190
  3. 200
  4. 400

Which simple sort makes the fewest swaps in the worst case?

  1. Bubble sort
  2. Selection sort
  3. Insertion sort
  4. They are equal

If you double n for an O(n²) algorithm, the work roughly...

  1. stays the same
  2. doubles
  3. quadruples
  4. grows by 2ⁿ