Sub topic 2
Counting the Work: Comparisons, Swaps, Shifts, and Extra Space
This chapter assumes you can write loops over a Python list by index and that you can read Big-O notation such as O(n) and O(n²). The goal is to agree on what "work" means before we analyze any sort. Each later chapter reports its costs in the units defined here.
Why a cost model matters
"Bubble sort is O(n²)" is true, but it is incomplete. Two sorts with the same Big-O can behave very differently in practice. One may compare often and move data rarely, and another may do the opposite. A cost model says which operations we count. Then we can see where each algorithm spends its time.
For in-place comparison sorts, we track four quantities.
| Measure | What is counted | When it dominates |
|---|---|---|
| Comparisons | Each evaluation of `a[x] < a[y]` or `a[x] > a[y]` | Keys are costly to compare, for example long strings or a slow key function |
| Swaps | Exchanging two elements, `a[i], a[j] = a[j], a[i]` | Records are large, or writes are slow (flash memory, network-backed storage) |
| Shifts | Copying one element one slot over, `a[j + 1] = a[j]` | Same as swaps, at roughly half the writes |
| Auxiliary space | Memory used beyond the input list | Memory is tight, or the data is too big to copy |
Swaps versus shifts
A swap and a shift both move data, but they cost different amounts. A swap writes two array slots. A shift writes one. Suppose an element must travel k positions to the left. You can do it with k adjacent swaps, which costs 2k writes. You can also save the element, shift the k elements in its way one slot right, and drop it into the gap. That costs k + 1 writes.
def move_left_by_swaps(a, i, j):
"""Move a[i] to index j (j <= i) with adjacent swaps; return array writes."""
writes = 0
while i > j:
a[i - 1], a[i] = a[i], a[i - 1]
writes += 2
i -= 1
return writes
def move_left_by_shifts(a, i, j):
"""Move a[i] to index j (j <= i) by shifting; return array writes."""
key = a[i]
writes = 0
while i > j:
a[i] = a[i - 1]
writes += 1
i -= 1
a[j] = key
return writes + 1
a = [2, 3, 4, 5, 1]
b = list(a)
print(move_left_by_swaps(a, 4, 0), a) # 8 [1, 2, 3, 4, 5]
print(move_left_by_shifts(b, 4, 0), b) # 5 [1, 2, 3, 4, 5]Both versions give the same result. The shift version writes to the list about half as often. Bubble sort moves data with swaps, and insertion sort moves it with shifts. That difference shows up again when we compare the two.
Auxiliary space
An in-place sort rearranges the input list and uses only O(1) extra memory: a few index variables and maybe one saved element. All three sorts in this tutorial are in place.
Python makes it easy to break this by accident. A slice such as a[pos:i] builds a new list. The expression sorted(a) returns a full O(n) copy. Neither is wrong, but code that uses them does not meet the strict O(1) space bound. We will see this trade-off in binary insertion sort, which uses a slice assignment to move a block of elements.
Common errors when counting
- Counting loop iterations instead of comparisons. A loop such as
while j >= 0 and a[j] > keymakes one fewer key comparison than it has condition checks when it stops becausejwent below 0. - Treating a swap and a shift as the same cost. A swap costs two writes, or three if a temporary variable is used.
- Reporting only Big-O. For small arrays, the constant factors decide which sort is faster.
- Forgetting the input itself. Auxiliary space excludes the n slots of the list being sorted.
Exercise
An element must move 6 positions to the left. How many array writes does this take with adjacent swaps, and how many with shifting? Which approach does insertion sort use?
Show answer
Adjacent swaps take 2 × 6 = 12 writes. Shifting takes 6 + 1 = 7 writes: six shifts plus one final write of the saved element. Insertion sort uses shifting.
Exercise
A function sorts a list by running b = list(a), sorting b in place with insertion sort, and returning b. What is its auxiliary space, and is it an in-place sort?
Show answer
It uses O(n) auxiliary space for the copy b, so it is not in place, even though the insertion sort step on b uses only O(1) extra space.