Code

Counting sort — fill in two holes

In the last step you watched counting sort in a table. Now the same thing is written down as an algorithm — and you fill in two missing pieces.

Pseudocode

Three passes, no comparisons.

CountingSortByRating(items):
    k ← MaxRating - MinRating + 1
    count ← array of k zeroes

    // 1. Count how many times each rating occurs.
    for each it in items:
        count[it.Rating - MinRating] += 1

    // 2. Prefix sums: count[v] becomes the index ONE PAST v's last
    //    position in the output.
    for i from 1 to k-1:
        count[i] += count[i-1]

    // 3. Place them. BACKWARDS — and that is what makes it stable.
    out ← array of len(items)
    for i from len(items)-1 down to 0:
        v ← items[i].Rating - MinRating
        count[v] -= 1
        out[count[v]] ← items[i]
        moves.Hit()
    return out

Read the third pass again. There is not a single comparison between two items. The key names the position directly.

The complexity is O(n + k): n for the passes over the data, k for the prefix sums.

Why backwards

The prefix sum gives the position of the last element with that value. Going from the end, the last item lands in the last slot of its block, the one before it in the one before, and the original order survives. It is the same G that went down first in the last step.

Go forwards and equal items come out reversed. One change of loop direction and stability is gone. Step 8 shows that this is not a detail.

cmp.Hit() — not once

Until now the counters measured how many comparisons. Here the test demands exactly zero.

The cmp parameter is still there — so the signature matches the other sorts, and so the test can prove the count is zero. If a cmp.Hit() appears anywhere, it has stopped being a counting sort.

moves.Hit() stays: one per element written into the output.

Your job

Create ncsort.go and ncsort_test.go (see the panel).

ncsort.go is complete and compiles, but it does not work: the three passes are written and two places are missing. They are marked HOLE 1 and HOLE 2:

  • HOLE 1 — the prefix sums. In the pseudocode that is count[i] += count[i-1]. The counted repeats are not yet positions until you add them up.
  • HOLE 2 — the placement itself: decrease count[v] by one and store items[i] into out[count[v]]. The first line is the v := ... from the pseudocode.

Nothing else needs changing. The loop already has the backwards direction and moves.Hit().

CountingSortByRating uses MinRating and MaxRating from item.go — the constants you wrote in lesson 1. Nothing new needs adding: the assumption this lesson depends on has been in your data type for eight lessons.

ncsort_test.go is the verdict — you do not write it, you pass it. For now it checks counting sort only:

  • the correct order and the same items — "sorted" does not yet mean "the same" (a slice of empty items is sorted too);
  • 0 comparisons and exactly n moves;
  • stability;
  • the table from the last step: A3 B1 C3 D0 E2 F1 G3 must come out as D B F E A C G, with 0 comparisons and 7 moves.

Run the test before you fill anything in

Run it as it stands first:

$ go test ./...
--- FAIL: TestCountingSortOrders
    ncsort_test.go:76: n=1: the output is not the same set of items as the input
--- FAIL: TestCountingSortIsStable
    ncsort_test.go:107: position 0 has ID 0, want 2 — not stable (got [0 0 0 0 0])
--- FAIL: TestCountingSortReproducesTheTable
    ncsort_test.go:122: the output reads , want DBFEACG
FAIL

That is not an error — it is the starting point. The skeleton tallies and walks the items, but puts nothing into out: the result is empty Item{}s. Notice that TestCountingSortMakesZeroComparisons already passes: the skeleton never compares and reports a move for every item. That is why the test also asks "is it the same set of items".

Fill in both holes and run it again — you should see ok.

When it does not pass

  • the output reads DBEA, want DBFEACG — items overwrite each other. You stored at count[v]-1 but did not decrement, so two items get the same slot.
  • panic: index out of range — you stored at out[count[v]] without decrementing: after the prefix sums count[v] can equal n, and the last slot is n-1.
  • the output reads ACG, want DBFEACG — HOLE 1 is empty: without the prefix sums count[v] is only a repeat count, not a position, and the items fall into the first slots.
  • the output reads DFBEGCA, want DBFEACG and not stable — you changed the loop direction to forwards. That is the same D F B E G C A you got with a pencil. The direction is already given — leave it.