Sub topic 8
Best, Average, and Worst Cases Side by Side
This chapter assumes you can read Python, know Big-O notation, and have seen the bubble, selection, and insertion sort implementations from the earlier chapters. Here we count the work each algorithm does and compare the counts. The question for each algorithm is how its comparisons and data moves change when the input is sorted, reversed, or random.
We use the cost model from earlier in the tutorial. A comparison is one evaluation of < or > between two elements. A swap exchanges two elements and costs three writes. A shift copies one element one slot to the right and costs one write. All three sorts use O(1) auxiliary space, so space never separates them. Time does.
Which inputs are best and worst
Each algorithm has a specific input that makes it do the least work and another that makes it do the most. For all three, the best input is already sorted. For bubble and insertion sort, the worst input is in reverse order. Selection sort is the exception: its comparison count is the same for every input, and its worst case for swaps is a rotation such as [2, 3, 4, ..., n, 1], not the reversed array.
In this chapter, "average case" means the expected cost over all n! orderings of n distinct keys, each equally likely. Average-case results are only as good as that assumption. Real data is often partly sorted, which is the subject of the next chapter.
Bubble sort with early exit
The version we analyze stops after the first pass that makes no swaps.
Best case (sorted input). The first pass compares each of the n − 1 adjacent pairs, finds nothing out of order, and the loop exits. The cost is n − 1 comparisons and 0 swaps, which is Θ(n).
Worst case (reversed input). Every pass swaps, so the early exit never fires. Pass i compares n − 1 − i pairs, for a total of
(n − 1) + (n − 2) + ... + 1 = n(n − 1)/2 comparisons,
and every one of those comparisons causes a swap. That is n(n − 1)/2 swaps, or 3n(n − 1)/2 writes.
Average case. Each adjacent swap fixes exactly one inversion, meaning one pair that is out of order. So the swap count equals the number of inversions in the input. A random permutation has n(n − 1)/4 inversions on average, because each of the n(n − 1)/2 pairs is out of order with probability 1/2. The comparison count stays close to n²/2. The early exit rarely saves much on random data, because the last few out-of-place small elements move left only one position per pass, so sorting needs almost n passes.
Selection sort
Comparisons in every case. Pass i scans positions i + 1 through n − 1 for the minimum. That scan always runs to the end, whatever the data looks like. The total is n(n − 1)/2 comparisons for sorted, reversed, and random input alike. Selection sort is Θ(n²) in every case.
Swaps. With the if m != i guard, a pass swaps only when the minimum is not already in place.
- Best case (sorted): 0 swaps.
- Worst case: n − 1 swaps. Rotated input such as
[2, 3, 4, 1]forces a swap on every pass. - Reversed input: only ⌊n/2⌋ swaps. Each swap puts two elements into their final positions at once.
- Average: n − Hₙ swaps, where Hₙ = 1 + 1/2 + ... + 1/n ≈ ln n. Each swap splits one cycle of the permutation into two, so the swap count is n minus the number of cycles in the input, and a random permutation has Hₙ cycles on average.
So selection sort makes the most comparisons of the three but at most 3(n − 1) writes. This is why it suits storage where writes are expensive.
Insertion sort
Best case (sorted). For each i from 1 to n − 1, the inner loop makes one comparison, sees a[i-1] <= key, and stops. That is n − 1 comparisons and 0 shifts, so Θ(n).
Worst case (reversed). Each new key is smaller than everything in the sorted prefix. So element i is compared with all i elements before it and shifted past all of them. Comparisons and shifts both total n(n − 1)/2.
Average case. Element i has on average i/2 larger elements before it. Summing over i gives about n(n − 1)/4 shifts and about n²/4 + n comparisons. Insertion sort therefore does about half the comparisons of the other two on random data.
The exact relationship is worth remembering:
- shifts = number of inversions, I
- comparisons = I + (n − 1) − (number of keys that travel all the way to index 0)
Each inner-loop iteration either shifts, which removes one inversion, or ends the loop. The loop ends with a comparison unless j runs off the front, which is what the last term accounts for. Writes come to I shifts plus n − 1 key placements.
The full picture
| Algorithm | Case | Comparisons | Swaps or shifts | Time |
|---|---|---|---|---|
| Bubble (early exit) | Best: sorted | n − 1 | 0 swaps | Θ(n) |
| Bubble (early exit) | Average | ~n²/2 | ~n²/4 swaps | Θ(n²) |
| Bubble (early exit) | Worst: reversed | n(n − 1)/2 | n(n − 1)/2 swaps | Θ(n²) |
| Selection | Best: sorted | n(n − 1)/2 | 0 swaps | Θ(n²) |
| Selection | Average | n(n − 1)/2 | n − Hₙ swaps | Θ(n²) |
| Selection | Worst: rotated | n(n − 1)/2 | n − 1 swaps | Θ(n²) |
| Insertion | Best: sorted | n − 1 | 0 shifts | Θ(n) |
| Insertion | Average | ~n²/4 | ~n²/4 shifts | Θ(n²) |
| Insertion | Worst: reversed | n(n − 1)/2 | n(n − 1)/2 shifts | Θ(n²) |
Big-O hides the differences that matter in practice. On random input all three sorts are Θ(n²). Insertion sort does about n²/4 comparisons and n²/4 single writes. Bubble sort does about n²/2 comparisons and n²/4 swaps, which is about 3n²/4 writes. On real hardware, insertion sort is usually several times faster than bubble sort even though both are "quadratic."
Where the cost comes from
Each algorithm's cost depends on the input in a different way. Knowing which counts depend on the input explains every row of the table.
Measuring the counts
The script below instruments all three sorts and runs them on sorted, reversed, and random inputs of size 100. Run it to check the formulas yourself.
import random
def bubble_counts(a):
a = list(a)
n = len(a)
comps = swaps = 0
for i in range(n - 1):
swapped = False
for j in range(n - 1 - i):
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
assert a == sorted(a)
return comps, swaps
def selection_counts(a):
a = list(a)
n = len(a)
comps = swaps = 0
for i in range(n - 1):
m = i
for j in range(i + 1, n):
comps += 1
if a[j] < a[m]:
m = j
if m != i:
a[i], a[m] = a[m], a[i]
swaps += 1
assert a == sorted(a)
return comps, swaps
def insertion_counts(a):
a = list(a)
comps = shifts = 0
for i in range(1, len(a)):
key = a[i]
j = i - 1
while j >= 0:
comps += 1
if a[j] > key:
a[j + 1] = a[j]
shifts += 1
j -= 1
else:
break
a[j + 1] = key
assert a == sorted(a)
return comps, shifts
def average(fn, n, trials, rng):
total_c = total_m = 0
for _ in range(trials):
data = list(range(n))
rng.shuffle(data)
c, m = fn(data)
total_c += c
total_m += m
return round(total_c / trials), round(total_m / trials)
n = 100
rng = random.Random(42)
inputs = {
"sorted": list(range(n)),
"reversed": list(range(n, 0, -1)),
}
for name, fn in [("bubble", bubble_counts),
("selection", selection_counts),
("insertion", insertion_counts)]:
print(name)
for label, data in inputs.items():
print(f" {label:9} comparisons, moves = {fn(data)}")
print(f" {'random':9} comparisons, moves = {average(fn, n, 200, rng)}")For n = 100, the sorted and reversed lines match the formulas exactly:
- Bubble:
(99, 0)sorted and(4950, 4950)reversed. - Selection:
(4950, 0)sorted and(4950, 50)reversed. - Insertion:
(99, 0)sorted and(4950, 4950)reversed.
The random averages land near the predictions. Insertion sort averages about 2475 shifts and about 2570 comparisons. Selection sort averages about 95 swaps (100 − H₁₀₀ ≈ 94.8). Bubble sort averages about 2475 swaps and a comparison count somewhat below 4950.
Common mistakes in this analysis
- Calling selection sort O(n) on sorted input. Its scans never stop early. Sorted input saves swaps, not comparisons.
- Counting insertion sort's moves as swaps. The shifting version does one write per move. A version that swaps neighbors does three writes per move, which makes it behave like bubble sort in write cost.
- Treating the average case as typical. The n²/4 figures assume uniformly random order. Logs, timestamps, and data that was appended to a sorted list are usually close to sorted, which pushes insertion and bubble sort toward their best case.
- Comparing only Big-O. Three algorithms with the same Θ(n²) can differ by a factor of 2 in comparisons and by a factor of n/3 in writes.
- Forgetting duplicates. With equal keys, the strict
>and<tests make fewer moves, because equal pairs are not inversions. The formulas above assume distinct keys and give upper bounds when there are duplicates.
Exercise
Selection sort is run on [3, 1, 2, 5, 4] with the if m != i guard. How many comparisons and how many swaps does it perform? Explain the swap count using cycles.
Show answer
Comparisons are always n(n-1)/2 = 10. In this permutation, position 0 holds 3, which belongs at index 2. Index 2 holds 2, which belongs at index 1. Index 1 holds 1, which belongs at index 0. That forms one 3-cycle. The values 5 and 4 form a 2-cycle. So there are 2 cycles, and swaps = n - cycles = 5 - 2 = 3. Tracing confirms it: swap indices 0 and 1 to get [1,3,2,5,4], swap indices 1 and 2 to get [1,2,3,5,4], no swap at index 2, then swap indices 3 and 4 to get [1,2,3,4,5].
Exercise
An input of n = 1000 distinct keys is sorted except that the smallest element sits at the last index. Compare the comparisons made by early-exit bubble sort and by insertion sort.
Show answer
The input has 999 inversions, all involving the last element. Insertion sort makes one comparison for each of the first 998 keys. The last key then shifts 999 times and runs off the front, so it adds 999 comparisons. That totals 1997 comparisons, which is Θ(n). Bubble sort moves the small element left only one position per pass, so it needs 999 passes and makes nearly all n(n-1)/2 = 499,500 comparisons, which is Θ(n²). The kind of disorder matters, not just how much there is.
Exercise
On random input of size n, roughly how many array writes does each algorithm make? Which one would you pick if writes cost 100 times more than comparisons?
Show answer
Bubble sort makes about n²/4 swaps, or about 3n²/4 writes. Insertion sort makes about n²/4 shifts plus n key placements, or about n²/4 writes. Selection sort makes about n - ln n swaps, or under 3n writes. If writes cost 100 times more than comparisons, pick selection sort. Its n²/2 comparisons cost less than insertion sort's roughly 25n² weighted write cost.