Sub topic 9
Insertion, Selection, and Bubble Sort
This chapter assumes you can read Python, count loop iterations, and use O, Omega, and Theta notation from the earlier chapters. It covers the three elementary quadratic sorts: how each works, how many comparisons and swaps each makes, and where each one is useful. Stability and adaptivity get a full treatment in the next chapter. Here they appear only where they change the cost analysis.
What the three sorts have in common
All three sorts run in place. They use O(1) extra memory and rearrange the array they are given. All three have a worst-case time of Theta(n^2) and use nested loops. They differ in how much work they do on favorable input, and in how many writes they make.
| Sort | Best case | Average case | Worst case | Swaps or moves (worst) | Extra space |
|---|---|---|---|---|---|
| Insertion | Theta(n) | Theta(n^2) | Theta(n^2) | Theta(n^2) | O(1) |
| Selection | Theta(n^2) | Theta(n^2) | Theta(n^2) | n - 1 swaps | O(1) |
| Bubble (with early exit) | Theta(n) | Theta(n^2) | Theta(n^2) | Theta(n^2) | O(1) |
Insertion sort
Insertion sort keeps a sorted prefix at the front of the array. At step i, it takes a[i] and slides it left past every larger element in the prefix until it finds the correct position.
def insertion_sort(a):
for i in range(1, len(a)):
key = a[i]
j = i - 1
while j >= 0 and a[j] > key:
a[j + 1] = a[j]
j -= 1
a[j + 1] = key
return a
print(insertion_sort([5, 2, 4, 6, 1, 3]))The inner loop runs once for every element in the prefix that is greater than the key. Such a pair, where an earlier element is larger than a later one, is called an inversion. The total number of inner-loop shifts equals the number of inversions in the input.
- Sorted input has 0 inversions. The inner loop never runs, so the total cost is n - 1 comparisons, which is Theta(n).
- Reverse-sorted input has n(n-1)/2 inversions, which is the maximum. The cost is Theta(n^2).
- A random permutation has n(n-1)/4 inversions on average, so the average case is also Theta(n^2).
The running time is therefore Theta(n + I), where I is the number of inversions. This makes insertion sort adaptive: it runs faster the closer the input is to sorted. A nearly sorted array, where each element is at most k positions from its final place, takes O(nk) time.
The algorithm is stable because the loop shifts only elements strictly greater than the key (>, not >=). Equal elements never pass each other.
Selection sort
Selection sort finds the minimum of the unsorted suffix and swaps it into the next position of the sorted prefix.
def selection_sort(a):
n = len(a)
for i in range(n - 1):
m = i
for j in range(i + 1, n):
if a[j] < a[m]:
m = j
a[i], a[m] = a[m], a[i]
return a
print(selection_sort([64, 25, 12, 22, 11]))The inner loop always scans the whole suffix, whatever the data looks like. The comparison count is
(n-1) + (n-2) + ... + 1 = n(n-1)/2
for every input, so the time is Theta(n^2) in the best, average, and worst cases. Selection sort is not adaptive.
Its advantage is the number of writes. It performs at most n - 1 swaps, which is Theta(n). If writing to memory is much more expensive than reading, as with some flash storage, selection sort can be the right choice among the quadratic sorts.
The swap makes this implementation unstable. In [4a, 4b, 2], the first step swaps 4a with 2 and gives [2, 4b, 4a]. The two equal 4s have changed their relative order.
Bubble sort
Bubble sort repeatedly compares adjacent elements and swaps them if they are out of order. After each pass, the largest remaining element has moved to its final position at the end.
def bubble_sort(a):
n = len(a)
for end in range(n - 1, 0, -1):
swapped = False
for j in range(end):
if a[j] > a[j + 1]:
a[j], a[j + 1] = a[j + 1], a[j]
swapped = True
if not swapped:
break
return a
print(bubble_sort([5, 1, 4, 2, 8]))The swapped flag stops the algorithm after a pass with no swaps. Without it, bubble sort always does n(n-1)/2 comparisons. With it, sorted input takes one pass of n - 1 comparisons, which is Theta(n).
Each swap of adjacent elements removes exactly one inversion. The number of swaps therefore equals the number of inversions, which is Theta(n^2) in the worst case. The algorithm is stable because it swaps only when a[j] > a[j + 1].
A subtle point: a small element moves left by only one position per pass, while a large element can move right many positions in one pass. The input [2, 3, 4, 5, 1] needs four passes, because the 1 travels one step per pass. The input [5, 1, 2, 3, 4] is sorted after one pass, because the 5 travels all the way to the end.
Counting operations on one input
Take [3, 1, 2], which has two inversions: (3,1) and (3,2).
| Sort | Comparisons | Swaps or shifts |
|---|---|---|
| Insertion | 3 | 2 shifts |
| Selection | 3 | 1 swap (3 and 1, giving `[1, 3, 2]`, then 3 and 2) |
Selection sort on this input actually does two swaps, because the second step swaps 3 with 2. The bound n - 1 = 2 is reached here. Bubble sort uses 3 comparisons in the first pass (two comparisons, then one in the second pass) and 2 swaps.
Common errors
- Saying insertion sort is Theta(n^2) in every case. The best case is Theta(n).
- Saying selection sort has a linear best case. The inner scan does not depend on the data.
- Forgetting the early-exit flag when asked about bubble sort's best case. The textbook version without it is Theta(n^2) on every input.
- Counting comparisons and swaps as the same thing. Selection sort has Theta(n^2) comparisons but only O(n) swaps.
- Calling the selection sort above stable. Stability requires shifting elements instead of swapping, which costs more writes.
Choosing among the three
- If the data is nearly sorted or arrives one item at a time, use insertion sort.
- If writes are expensive and n is small, selection sort minimizes them.
- Bubble sort has no practical advantage over insertion sort. Its main value is as a teaching example and as an exam topic.
Exercise
An array of n distinct elements is sorted in reverse order. Give the exact number of comparisons and swaps (or shifts) that insertion sort makes, counting each comparison in the inner while condition that involves array elements.
Show answer
Each element at index i is greater than every element before it reversed, so it is shifted past all i elements in the prefix. The shifts total 1 + 2 + ... + (n-1) = n(n-1)/2. Each shifted element needs one comparison, and the loop ends because j reaches -1 without a further element comparison. So there are n(n-1)/2 comparisons and n(n-1)/2 shifts. The time is Theta(n^2).
Exercise
An array has n elements, and exactly one adjacent pair is out of order, for example [1, 2, 4, 3, 5, 6]. State the running time of insertion sort, of selection sort, and of bubble sort with the early-exit flag.
Show answer
The input has exactly one inversion. Insertion sort runs in Theta(n + 1) = Theta(n). Selection sort runs in Theta(n^2) because it always scans the whole suffix. Bubble sort with the flag needs one pass that fixes the pair and a second pass that finds no swaps, so it runs in Theta(n).