Sub topic 2
Counting the Work: Comparisons, Swaps, Shifts, and Extra Space
This chapter assumes you can write loops over a list by index, read Python, and recognize Big-O notation such as O(n) and O(n²). It does not teach the three sorts yet. It defines the units we will use to measure them, so that later claims such as "selection sort makes at most n − 1 swaps" have an exact meaning.
Why "Running Time" Is Too Coarse
Timing a sort with a stopwatch mixes many effects together: the interpreter, the cache, the type of the keys, and the size of each record. To compare algorithms, we count the abstract operations that every comparison sort must perform. Then we ask which of those operations is expensive in a given setting.
Elementary sorts do four kinds of work:
- Comparisons: asking whether one key is less than another.
- Swaps: exchanging the values at two positions.
- Shifts: copying one value into a neighboring position, usually to open a gap.
- Extra space: memory used beyond the input array itself.
Two algorithms can both run in O(n²) time and still differ by a factor of ten in one of these counts. That difference is often the whole reason to pick one over the other.
Comparisons
A key comparison is any evaluation of <, >, or <= between two elements being sorted (or between their keys). Comparisons are the standard unit for comparison sorts because the algorithm learns about the input only by comparing.
Comparisons become expensive when:
- keys are long strings that share prefixes, so each comparison scans many characters,
- keys are tuples compared field by field,
- a
key=function or custom comparator runs on every comparison, - comparison calls into user code, as Python's
__lt__does for objects.
Swaps and Shifts Are Different Units
Both swaps and shifts move data, but they cost different amounts.
A swap exchanges a[i] and a[j]. Written out, it takes three assignments: save one value in a temporary, copy the second into the first slot, then copy the temporary into the second slot. Two of those assignments write to the array.
A shift copies a[j] into a[j + 1]. That is one array write. An algorithm that shifts holds the element being placed in a local variable and writes it once at the end, into the gap the shifts opened.
To compare them fairly, we use a shared unit: array writes, meaning assignments into a position of the list.
| Operation | Array writes | Typical use |
|---|---|---|
| Swap of two positions | 2 (plus one temporary) | Exchanging adjacent or distant elements |
| Shift by one position | 1 | Sliding a run of elements to open a gap |
| Final placement of a held key | 1 | Dropping the saved element into the gap |
Moving one element k positions left costs 2k array writes with adjacent swaps. With shifts it costs k + 1 writes: k shifts plus one placement. For large k, shifting does about half the writes.
Measuring It: An Instrumented Example
The code below wraps comparisons and writes in a small meter object. It moves the last element of [2, 4, 6, 8, 1] to its correct place in two ways: by repeated adjacent swaps, and by shifting.
class Meter:
def __init__(self):
self.comparisons = 0
self.writes = 0
def less(self, x, y):
self.comparisons += 1
return x < y
def swap(self, a, i, j):
a[i], a[j] = a[j], a[i]
self.writes += 2
def write(self, a, i, value):
a[i] = value
self.writes += 1
def sink_by_swaps(a, m):
i = len(a) - 1
while i > 0 and m.less(a[i], a[i - 1]):
m.swap(a, i, i - 1)
i -= 1
def sink_by_shifts(a, m):
i = len(a) - 1
key = a[i]
while i > 0 and m.less(key, a[i - 1]):
m.write(a, i, a[i - 1]) # shift right by one
i -= 1
m.write(a, i, key) # drop the held key into the gap
for name, fn in [("swaps", sink_by_swaps), ("shifts", sink_by_shifts)]:
data = [2, 4, 6, 8, 1]
m = Meter()
fn(data, m)
print(name, data, "comparisons:", m.comparisons, "writes:", m.writes)
# swaps [1, 2, 4, 6, 8] comparisons: 4 writes: 8
# shifts [1, 2, 4, 6, 8] comparisons: 4 writes: 5Both versions make 4 comparisons, because they ask the same questions in the same order. The swap version writes 8 times and the shift version writes 5 times. In the loop i > 0 and m.less(...), the and short-circuits, so no key comparison happens once i reaches 0. That detail decides whether your count is n − 1 or n.
Counting Nested Loops
Elementary sorts share one loop shape: an outer index i, and an inner index that covers the remaining part of the array. The number of inner iterations is a sum you will see in every later chapter.
def count_pairs(n):
count = 0
for i in range(n - 1):
for j in range(i + 1, n):
count += 1
return count
for n in [1, 2, 5, 10, 100]:
print(n, count_pairs(n), n * (n - 1) // 2)
# 1 0 0
# 2 1 1
# 5 10 10
# 10 45 45
# 100 4950 4950The inner loop runs (n − 1) + (n − 2) + … + 1 times, which equals n(n − 1)/2. That count is the number of distinct pairs of positions, and it grows as Θ(n²). An algorithm that compares every pair once makes exactly this many comparisons on every input. An algorithm whose inner loop can stop early makes anywhere from about n to n(n − 1)/2, depending on the data. Later chapters build on this distinction between a fixed count and a data-dependent one.
Extra Space and the Meaning of "In Place"
Auxiliary space is memory an algorithm uses beyond the input. An algorithm is in place if its auxiliary space is O(1): a fixed number of index variables and at most one or two temporaries, regardless of n.
All three sorts in this tutorial are in place. They need loop indices, perhaps a swapped flag, and one held value. Merge sort, by contrast, typically allocates an O(n) buffer.
Several details catch people out:
- Copies count. A function that starts with
a = list(a)uses O(n) extra space, even if the rest of it is in place. Python'ssorted()returns a new list.list.sort()sorts the list it is called on. - Recursion counts. Every active call frame takes stack space. A recursive algorithm with depth log n uses O(log n) space even though it allocates no arrays. Strict definitions do not call that in place.
- Tuple swaps are still O(1). In Python,
a[i], a[j] = a[j], a[i]builds a temporary pair, but its size does not depend on n. - Slice assignment allocates.
a[p+1:i+1] = a[p:i]builds a temporary slice of length i − p. That costs O(n) space in the worst case, though the memory is released straight away.
Which Count Matters When
No single count is "the" cost. The setting decides which one dominates.
| Setting | Dominant cost | Why |
|---|---|---|
| Sorting Python objects by a `key=` function | Comparisons | Each comparison calls interpreted code |
| C array of 4 KB structs, sorted by value | Writes | Each move copies 4 KB of memory |
| Array of pointers or references | Comparisons | A move copies one machine word |
| Data stored in flash memory | Writes | Each write wears the memory cells |
| Microcontroller with 2 KB of RAM | Extra space | No room for a second buffer |
The third row matters for Python. A Python list stores references, so a swap moves two pointers no matter how large the objects are. Write cost matters much more in languages that store records inline, or when the data lives on a device where writes are slow or wear the hardware out.
Common Counting Errors
- Counting a swap as one write. A swap writes two array positions. If you compare swap-based and shift-based code, convert both to array writes first.
- Forgetting the final placement. A shift-based routine that moves an element k places performs k + 1 writes, not k.
- Counting swaps that do nothing. Code that swaps
a[i]with itself still costs writes unless it testsif m != ifirst. - Ignoring short-circuit evaluation. When the index test fails first, the key comparison never runs, so it is not counted.
- Using one input to judge an algorithm. Counts that depend on the data must be measured on best, typical, and worst inputs, not on one example.
Exercise
You reverse a list of n elements in place by swapping a[0] with a[n-1], a[1] with a[n-2], and so on until the indices meet. How many key comparisons, swaps, and array writes does this take, and how much auxiliary space?
Show answer
Zero key comparisons, because no keys are compared. There are floor(n/2) swaps, which is 2 * floor(n/2) array writes. Auxiliary space is O(1): two indices and one temporary.
Exercise
An element must move 10 positions to the left. How many array writes does it take with adjacent swaps, and how many with shifts followed by one final placement?
Show answer
Adjacent swaps: 10 swaps at 2 writes each, so 20 writes. Shifts: 10 shifts plus 1 placement, so 11 writes.
Exercise
A function begins with b = a[:], sorts b using only index variables and one temporary, then copies b back into a. Is it in place? Explain using auxiliary space.
Show answer
No. The copy b takes O(n) extra memory, so auxiliary space is O(n). The sorting loop on its own uses O(1) space, but auxiliary space covers the whole function.
Exercise
In the loop while j >= 0 and a[j] > key:, the body runs 3 times and then the loop exits because j becomes -1. How many key comparisons were made? What if it exits instead because a[j] > key is false while j is still 0 or more?
Show answer
In the first case there were 3 key comparisons. The final test stops at j >= 0 and never evaluates a[j] > key. In the second case there were 4: three that returned true and one that returned false.