Insertion sort — fill in two holes
In the last step you watched insertion sort in a table. Now the same thing is written down as an algorithm — and you fill in two missing pieces.
Pseudocode
for i from 1 to n-1:
cur ← items[i]
j ← i - 1
while j >= 0:
cmp.Hit()
if items[j].Title <= cur.Title: break
items[j+1] ← items[j]
swap.Hit()
j ← j - 1
items[j+1] ← cur
This is exactly what you did by hand on the i=4 row: take cur, compare it with
the neighbour on the left; if the neighbour is larger, shift it right and go on;
if not, stop and put cur in the free slot.
The line that matters is if items[j].Title <= cur.Title: break.
It stops the shifting the moment the place is found. If the slice is already sorted, every item needs exactly one comparison, and the whole sort costs n−1 comparisons and zero swaps. Remember it; step 7 shows what it is worth.
<=, not <. With <, equal items would still shift past each other and
stability would be gone. The test will catch it.
Your job
Create sort.go and sort_test.go (see the panel).
sort.go is complete and compiles, but it does not work: the loops are
written and two places are missing. They are marked HOLE 1 and HOLE 2:
- HOLE 1 — the condition for when shifting stops. In the pseudocode that is
if … <= …: break. Replacefalsewith a real condition. - HOLE 2 — the shift itself:
items[j+1] ← items[j]and counting it.
Nothing else needs changing. The loops already contain cmp.Hit(), j-- and the
final items[j+1] = cur.
sort_test.go is the verdict — you do not write it, you pass it. For now it
checks insertion sort only.
The test also checks the table from the last step: [5 2 4 1 3] must take
9 comparisons and 7 shifts. If your code counts differently, something is
off even if the result comes out sorted.
Run the test before you fill anything in
Run it as it stands first:
$ go test ./...
--- FAIL: TestSortsProduceSortedOutput/insertion
sort_test.go:39: n=3: not sorted at 2
--- FAIL: TestStableSortsKeepEqualTitlesInOrder/insertion
sort_test.go:65: position 0 has ID 5, want 2 — not stable (got [5 2 3 4 5])
--- FAIL: TestComparisonCountsAreExact/insertion_on_sorted_input_does_exactly_n-1
sort_test.go:108: comparisons = 4950, want 99
--- FAIL: TestComparisonCountsAreExact/insertion_reproduces_the_table_from_the_lesson
sort_test.go:119: comparisons / swaps = 10 / 0, want 9 / 7
FAIL
That is not an error — it is the starting point. The skeleton sorts nothing and
compares every item with everything on its left: 4950 = 100·99/2, where 99 is
required.
Fill in both holes and run it again — you should see ok.
When it does not pass
not stable— you most likely wrote<instead of<=. Equal items jump over each other.comparisons / swaps = 9 / 0, want 9 / 7— you shifted but did not count. Every shift needs aswap.Hit().not sorted, with repeated numbers in the result (e.g.[2 2 4 4 5]) — you counted but did not shift. The slot kept its old value, andcurwas put down in only one place.