Sub topic 10
Inversions and Why Nearly Sorted Input Favors Insertion Sort
This chapter assumes you already know the in-place implementations of bubble sort (with the early-exit check), selection sort, and insertion sort from earlier chapters. It also assumes you are comfortable with Big-O notation and with counting comparisons and moves. Here we introduce one measure of disorder, the inversion count, and use it to explain why insertion sort is fast on nearly sorted data, why bubble sort is only partly fast on it, and why selection sort ignores presortedness entirely.
What an Inversion Is
An inversion in an array a is a pair of indices (i, j) with i < j and a[i] > a[j]. It is a pair of elements that are in the wrong order relative to each other. The comparison is strict, so two equal keys never form an inversion.
The inversion count I measures how far an array is from sorted:
| Input | Inversion count |
|---|---|
| Sorted ascending | 0 |
| Sorted descending, distinct keys | n(n-1)/2 |
| Random permutation of distinct keys (expected) | n(n-1)/4 |
| Sorted except one adjacent pair swapped | 1 |
The random-permutation figure follows from symmetry. Each of the n(n-1)/2 pairs is equally likely to appear in either order, so each pair is inverted with probability 1/2.
The brute-force count below checks every pair, so it takes O(n²) time. That is fine for experiments. A merge-sort-based counter does it in O(n log n), but we do not need one here.
def count_inversions(a):
n = len(a)
return sum(1 for i in range(n) for j in range(i + 1, n) if a[i] > a[j])
print(count_inversions([3, 1, 4, 1, 5, 9, 2, 6])) # 8
print(count_inversions([1, 2, 3, 4])) # 0
print(count_inversions([4, 3, 2, 1])) # 6The Key Fact: An Adjacent Swap Removes Exactly One Inversion
Suppose a[k] > a[k+1] and you swap them. Only one pair changes its relative order: the pair at positions k and k+1. Every other element x still sits either before both of them or after both, so whether x is inverted with each of them stays the same. The swapped pair was an inversion and now is not. The net change is exactly −1.
This has three consequences:
- Any algorithm that only exchanges adjacent out-of-order elements performs exactly
Iexchanges to sort the array. - On a random permutation, such an algorithm performs about n²/4 exchanges on average. So any adjacent-exchange sort is Ω(n²) on average, however clever its control flow. Faster sorts such as merge sort and quicksort move elements across long distances, and one move can fix many inversions at once.
- Swapping equal adjacent elements would not remove an inversion. That is why bubble sort and insertion sort use strict
>and never touch equal keys, which keeps them stable.
Insertion Sort Does Θ(n + I) Work
Insertion sort's inner loop shifts an element one slot right whenever it is greater than key. A shift plus the final drop of key into the gap has the same effect as a series of adjacent swaps that carry key leftward. Each shift moves key past one larger element that sat before it, and that removes exactly one inversion. So the total number of shifts equals I.
def count_inversions(a):
n = len(a)
return sum(1 for i in range(n) for j in range(i + 1, n) if a[i] > a[j])
def insertion_sort_shifts(a):
a = list(a)
shifts = 0
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
shifts += 1
a[j + 1] = key
return shifts
data = [3, 1, 4, 1, 5, 9, 2, 6]
print(count_inversions(data), insertion_sort_shifts(data)) # 8 8Comparisons follow from shifts. For each i, every comparison that finds a[j] > key causes one shift. At most one more comparison fails and stops the loop. The loop can also end because j fell below 0, in which case no failing comparison happens. Summed over the n−1 outer iterations, this gives:
- comparisons = I + (n − 1) − z, where z is the number of keys that travelled all the way to index 0.
- Therefore I ≤ comparisons ≤ I + n − 1.
Insertion sort's running time is Θ(n + I). It is linear when I is O(n) and quadratic when I is Θ(n²). An algorithm whose cost shrinks as the input gets closer to sorted is called adaptive. Insertion sort is adaptive in the strongest sense this chapter covers: its cost tracks the inversion count exactly.
What "nearly sorted" means in practice
Two common definitions both give a linear or near-linear bound:
- Few inversions: if I ≤ c·n for a constant c, insertion sort runs in O(n).
- Each element within k positions of its final place: an element x can only be inverted with elements whose positions overlap its window. That gives fewer than 2k inversions per element, so I < 2kn and insertion sort runs in O(nk). Examples include timestamps that arrive slightly out of order, or a sorted list after a few local edits.
Bubble Sort: Swaps Track Inversions, Comparisons Do Not
Bubble sort swaps only adjacent out-of-order pairs, so it also performs exactly I swaps. Its comparison count, however, depends on how many passes it makes, and each pass costs up to n−1 comparisons regardless of how many swaps happen.
The number of passes depends on the shape of the disorder. In one pass, a large element can travel any distance to the right, because it keeps winning comparisons. A small element can move at most one position to the left, because it gets swapped once and the scan moves past it. Programmers call these "rabbits" (large elements near the front, which move fast) and "turtles" (small elements near the back, which move slowly). More precisely, the number of swapping passes equals the largest number of greater elements that appear before any single element. Early exit adds one more pass to confirm that the array is sorted, unless the loop already stopped after n−1 passes.
Compare two inputs of size 10 that each contain exactly 9 inversions:
- turtle:
[2, 3, 4, 5, 6, 7, 8, 9, 10, 1], where the 1 must crawl left one step per pass. - rabbit:
[10, 1, 2, 3, 4, 5, 6, 7, 8, 9], where the 10 bubbles to the end in a single pass.
def bubble_counts(a):
a = list(a)
n = len(a)
comps = swaps = passes = 0
for i in range(n - 1):
passes += 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
return comps, swaps, passes
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]
j -= 1
shifts += 1
else:
break
a[j + 1] = key
return comps, shifts
turtle = list(range(2, 11)) + [1]
rabbit = [10] + list(range(1, 10))
print("turtle bubble (comps, swaps, passes):", bubble_counts(turtle))
print("turtle insertion (comps, shifts): ", insertion_counts(turtle))
print("rabbit bubble (comps, swaps, passes):", bubble_counts(rabbit))
print("rabbit insertion (comps, shifts): ", insertion_counts(rabbit))
# turtle bubble (comps, swaps, passes): (45, 9, 9)
# turtle insertion (comps, shifts): (17, 9)
# rabbit bubble (comps, swaps, passes): (17, 9, 2)
# rabbit insertion (comps, shifts): (17, 9)Both algorithms make 9 moves on both inputs, matching I = 9. Insertion sort makes 17 comparisons on both. Bubble sort makes 17 comparisons on the rabbit input and 45 on the turtle input. Forty-five is n(n−1)/2, the maximum possible, even though the array has only n−1 inversions. In general, the turtle input costs bubble sort Θ(n²) comparisons and insertion sort 2n−3 comparisons.
Early exit makes bubble sort adaptive only to inputs whose disorder is "rabbit-shaped." Insertion sort is adaptive to every kind of small disorder. This gap is the main reason insertion sort, not bubble sort, is the elementary sort used in practice.
Selection Sort Ignores Inversions
Selection sort always scans the whole unsorted suffix to find its minimum, so it makes n(n−1)/2 comparisons whether I is 0 or n(n−1)/2. Its swap count is at most n−1 and does not equal I. One long-distance swap can remove many inversions at once, and it can also create new ones among the elements it jumps over. This explains both of selection sort's traits: few writes, and no adaptivity.
Summary Table
| Algorithm | Moves as a function of I | Comparisons | Adaptive to inversions? |
|---|---|---|---|
| Insertion sort | shifts = I | between I and I + n − 1 | Yes, Θ(n + I) |
| Bubble sort, early exit | swaps = I | (passes) × up to n − 1; between n − 1 and n(n−1)/2 | Partly: depends on how far elements must move left |
| Selection sort | swaps ≤ n − 1, unrelated to I | always n(n−1)/2 | No |
Checking the Bounds Yourself
The script below tests the insertion-sort identities on many random arrays, including arrays with duplicate keys. It uses a fixed seed and prints only whether every check passed, so the output is deterministic.
import random
def count_inversions(a):
n = len(a)
return sum(1 for i in range(n) for j in range(i + 1, n) if a[i] > a[j])
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]
j -= 1
shifts += 1
else:
break
a[j + 1] = key
assert a == sorted(a)
return comps, shifts
random.seed(42)
ok = True
for _ in range(500):
n = random.randint(1, 40)
data = [random.randint(0, 15) for _ in range(n)] # duplicates allowed
inv = count_inversions(data)
comps, shifts = insertion_counts(data)
if shifts != inv or not (inv <= comps <= inv + n - 1):
ok = False
print("counterexample:", data)
break
print("all checks passed" if ok else "a check failed")
# all checks passedExercises
Exercise
Count the inversions in [5, 1, 4, 2, 3]. How many shifts will insertion sort perform, and how many swaps will bubble sort perform?
Show answer
The inverted pairs are (5,1), (5,4), (5,2), (5,3), (4,2), and (4,3), so I = 6. Both algorithms move only adjacent out-of-order elements, and each such move removes exactly one inversion. Insertion sort therefore performs 6 shifts and bubble sort performs 6 swaps.
Exercise
The array [2, 3, ..., n, 1] has only n − 1 inversions. Explain why bubble sort with early exit still makes Θ(n²) comparisons on it, while insertion sort makes 2n − 3.
Show answer
In each bubble pass, the 1 is swapped with its left neighbor once and then the scan moves past it, so it moves left only one position per pass. It needs n − 1 passes to reach index 0, and those passes cost (n−1) + (n−2) + ... + 1 = n(n−1)/2 comparisons. Insertion sort makes one comparison for each of the first n − 2 keys, because each is already larger than its predecessor. It then makes n − 1 comparisons to carry the 1 to the front, for a total of 2n − 3.
Exercise
A log file's records are sorted by timestamp, except that each record can be at most 3 positions away from its correct place. Give a bound on insertion sort's running time for n records and justify it.
Show answer
Each record is within k = 3 positions of its final place, so it can be inverted only with records in a window of fewer than 2k positions around it. That gives I < 2kn = 6n. Insertion sort runs in Θ(n + I), which is O(n) here. More generally, the bound is O(nk).
Exercise
Prove that any sorting algorithm that changes the array only by swapping adjacent elements needs Ω(n²) swaps on average over random permutations of distinct keys.
Show answer
An adjacent swap changes the relative order of exactly one pair, so it lowers the inversion count by at most one. A sorted array has 0 inversions, so the algorithm needs at least I swaps. For a random permutation, each of the n(n−1)/2 pairs is inverted with probability 1/2, so the expected I is n(n−1)/4. That makes the expected number of swaps at least n(n−1)/4, which is Ω(n²).