Table sort
Instead of moving large records around, sort a table of indices, then move each record just once, following the cycles of the permutation.
If each record is large (say, a student's file), moving it is expensive. Table sort works in two steps:
Read the full explanation ↓- Time:
O(n²) comparisons, O(n) record moves - Space:
O(n) - Horowitz–Sahni, chapter 7
Six records; the index table is sorted, then one cycle of four is followed (14 and 50 are already in place).
def table_sort(a):n = len(a)# 1. Sort a table of indices instead of the (large) records themselves.t = list(range(n))for i in range(1, n):j = iwhile j > 0 and a[t[j - 1]] > a[t[j]]:t[j - 1], t[j] = t[j], t[j - 1]j = j - 1# 2. Move each record once, following the cycles of the permutation t.for i in range(n):if t[i] == i:continuetemp = a[i]j = iwhile t[j] != i:k = t[j]a[j] = a[k]t[j] = jj = ka[j] = tempt[j] = jreturn a
Start
Local variables
Orange = changed in this step
a list
351412422650
Call stack
- table_sort()line 1
Step 1 of 73
How the work grows with input size
Average of 12 random graphs per n (fixed seeds). Hollow marker = the input on screen.
- swap_index
- move
- current input (n=6)
Show as a table
| n | swap_index | move |
|---|---|---|
| 4 | 3.3 | 2.2 |
| 6 | 7.6 | 4.1 |
| 8 | 12 | 5 |
| 10 | 21.3 | 6.3 |
| 12 | 29.4 | 9.3 |
Explanation
The idea
If each record is large (say, a student's file), moving it is expensive. Table sort works in two steps:
- Sort a table of indices: sort an array
tof indices so thata[t[0]] ≤ a[t[1]] ≤ …. The records do not move at all; only the small numbers intdo. (Sometimes that is enough: read the records in the order oft.) - Move the records:
tis a permutation, and every permutation is made of cycles. In each cycle, keep one record aside, move each of the others once into its final place, and put the kept record into the last free place.
Cost
Step 2 moves each record at most once: O(n) record moves, against O(n²) in a plain insertion sort.
What to watch in the trace
- In step 1 the bars stand still and only
tchanges in the memory panel; in step 2 the bars go to their places cycle by cycle.