Sub topic 10
Inversions and Why Nearly Sorted Input Favors Insertion Sort
This chapter assumes you can read Big-O notation and that you know the in-place versions of bubble, selection, and insertion sort from earlier chapters, including bubble sort's early-exit check. The question here is concrete. If an array is already almost in order, how much work does each sort skip? A single number, the inversion count, answers that.
What an Inversion Is
An inversion is a pair of positions i < j where a[i] > a[j]. It is a pair of elements that sit in the wrong order relative to each other.
- A sorted array has 0 inversions.
- A reverse-sorted array of length n has n(n-1)/2 inversions, the maximum, because every pair is out of order.
- A random permutation has n(n-1)/4 inversions on average, because each pair is out of order with probability 1/2.
So the inversion count measures how unsorted an array is, on a scale from 0 to n(n-1)/2.
Each Adjacent Fix Removes Exactly One Inversion
When you swap two neighbors a[j] > a[j+1], only that one pair changes its relative order. Every other pair keeps its relative order. The swap therefore removes exactly one inversion. Insertion sort's shift moves key one step left past a single larger element, so it has the same effect.
That gives two exact results:
- Bubble sort performs exactly I swaps, where I is the number of inversions.
- Insertion sort performs exactly I shifts.
Insertion sort also makes at most one "failed" comparison per element, the one that stops the inner loop. Its comparison count is therefore between I and I + (n - 1), and its running time is Θ(n + I). When I is O(n), as it is for nearly sorted data, insertion sort runs in linear time. An algorithm whose cost shrinks as the input gets closer to sorted is called adaptive.
Why Bubble Sort Adapts Less Well
Bubble sort's swap count also equals I, but its comparisons depend on how many passes it needs. A small value near the end of the array (often called a "turtle") moves left only one position per pass. A single misplaced element can therefore force nearly n passes, even though the array has only n - 1 inversions.
Selection sort does not adapt at all. It always makes n(n-1)/2 comparisons, whatever the input.
The code below counts the work on [2, 3, ..., 10, 1], which has only 9 inversions:
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 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
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:
break
a[j + 1] = a[j]
j -= 1
shifts += 1
a[j + 1] = key
return comps, shifts
data = list(range(2, 11)) + [1]
print("inversions:", count_inversions(data)) # inversions: 9
print("bubble:", bubble_counts(data)) # bubble: (45, 9)
print("insertion:", insertion_counts(data)) # insertion: (17, 9)Both sorts do 9 moves, one per inversion. Bubble sort needs all 9 passes and 45 comparisons. Insertion sort needs 17 comparisons.
Summary of Adaptivity
| Algorithm | Moves | Comparisons on nearly sorted input |
|---|---|---|
| Insertion sort | I shifts | Between I and I + n - 1, linear when I = O(n) |
| Bubble sort (early exit) | I swaps | Depends on how far the smallest misplaced value must travel; can be Θ(n²) |
| Selection sort | At most n - 1 swaps | Always n(n-1)/2 |
Exercise
The array [1, 2, 3, 5, 4, 6, 8, 7] has how many inversions, and how many shifts and comparisons does insertion sort make on it (counting comparisons as in insertion_counts above)?
Show answer
There are 2 inversions, (5, 4) and (8, 7), so insertion sort makes 2 shifts. Each of the 7 elements from index 1 onward makes one comparison that stops its inner loop. The elements 4 and 7 each also make one comparison that triggers a shift, giving 7 + 2 = 9 comparisons, which equals I + (n - 1).
Exercise
Why does every adjacent swap in bubble sort reduce the inversion count by exactly one?
Show answer
Swapping neighbors a[j] > a[j+1] reverses the relative order of only that pair. Every other element stays on the same side of both swapped elements, so no other pair changes its order. The pair goes from inverted to ordered, and the count drops by exactly 1.