Sub topic 8
Best, Average, and Worst Cases Side by Side
This chapter assumes you can read Big-O notation and that you already know how bubble sort (with early exit), selection sort, and insertion sort work. It also uses the cost model from earlier: comparisons, swaps, shifts, and extra space. Here the three sorts are measured with the same counters, so you can see where they actually differ.
The three input shapes
Three inputs of length n mark out the range of behavior:
- Sorted: already in order. This is the best case for any sort that can detect order.
- Reversed: in descending order. Every pair is out of order, so this is the worst case for bubble and insertion sort.
- Random: a uniformly random permutation. This is the average case.
The average case for bubble and insertion sort depends on how many pairs start out of order. A random permutation has n(n-1)/4 such pairs on average, which is half of all pairs.
The summary table
| Algorithm | Comparisons (best / avg / worst) | Swaps or shifts (best / avg / worst) | Extra space |
|---|---|---|---|
| Bubble (early exit) | n-1 / ~n²/2 / n(n-1)/2 | 0 / n(n-1)/4 / n(n-1)/2 swaps | O(1) |
| Selection | n(n-1)/2 in every case | 0 / about n / n-1 swaps | O(1) |
| Insertion | n-1 / ~n²/4 / n(n-1)/2 | 0 / n(n-1)/4 / n(n-1)/2 shifts | O(1) |
A few points in the table are easy to miss:
- Selection sort makes the same number of comparisons on every input. It always scans the whole unsorted suffix to find the minimum, so it is Θ(n²) even on sorted data.
- Bubble sort's early exit helps on sorted or almost sorted input. On random input it still averages about n²/2 comparisons, because the final pass with no swaps usually comes late.
- Insertion sort averages about half as many comparisons as bubble sort. Each insertion stops as soon as it finds a smaller-or-equal element, so it scans about half the sorted prefix on average.
Measuring it yourself
The script below counts comparisons and moves for each sort. A move is one swap for bubble and selection sort, and one shift for insertion sort.
import random
def bubble(a):
a = list(a); n = len(a); comps = moves = 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]
moves += 1
swapped = True
if not swapped:
break
return comps, moves
def selection(a):
a = list(a); n = len(a); comps = moves = 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]
moves += 1
return comps, moves
def insertion(a):
a = list(a); comps = moves = 0
for i in range(1, len(a)):
key = a[i]; j = 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 = 8
rand = list(range(1, n + 1))
random.seed(1)
random.shuffle(rand)
inputs = {"sorted": list(range(1, n + 1)),
"reversed": list(range(n, 0, -1)),
"random": rand}
for name, fn in [("bubble", bubble), ("selection", selection), ("insertion", insertion)]:
for label, data in inputs.items():
c, m = fn(data)
print(f"{name:<10}{label:<10}{c:>5}{m:>5}")With n = 8 we have n(n-1)/2 = 28, and the sorted and reversed rows come out like this:
| Algorithm | Sorted (comps, moves) | Reversed (comps, moves) |
|---|---|---|
| Bubble | 7, 0 | 28, 28 |
| Selection | 28, 0 | 28, 4 |
| Insertion | 7, 0 | 28, 28 |
Selection sort makes only 4 swaps on the reversed array. Each swap fixes both ends of the array at once, so it needs n/2 swaps instead of n-1. On random input, bubble sort and insertion sort make the same number of moves as each other, but insertion sort makes fewer comparisons.
How the counts grow
All three sorts are O(n²) in the worst case, so Big-O alone cannot separate them. Separate them by their constant factors, by how they handle the best case, and by whether moves or comparisons are the expensive operation.
Exercise
For n = 1000, give the number of comparisons each sort makes on an already sorted array, and say which sort's count does not change on reversed input.
Show answer
Bubble sort with early exit makes 999 comparisons and insertion sort makes 999. Selection sort makes 1000 × 999 / 2 = 499,500. Selection sort's count is also 499,500 on reversed input, because it always scans the whole unsorted suffix.
Exercise
On a random array of 200 elements, about how many shifts does insertion sort perform, and about how many swaps does bubble sort perform?
Show answer
Both equal the number of out-of-order pairs, which averages n(n-1)/4 = 200 × 199 / 4 = 9,950. Each swap writes two slots and each shift writes one, so bubble sort does about twice as many array writes.