Counting sort and bucket sort: sorting without comparisons

Video lessonComing soon

1 Sorting sheets onto trays

The teacher from the sorting lesson has six new answer sheets, marked out of 5. They are in roll order:

3Anu1Ben4Charu1Dev0Esha3Farah
Six sheets in roll order. Each box holds the marks, with the name below

Merge sort and quick sort compare two values at a time and take about n log n steps. No sort that compares can do better in the worst case. Each comparison answers only yes or no, and telling apart all the orders n values can come in takes about n log n such answers.

The teacher does not compare sheets at all. She puts six trays on her desk, labelled 0 to 5. She reads each sheet's mark and puts the sheet on that tray, behind any sheets already there. Then she collects the trays from 0 to 5.

0Esha1BenDev23AnuFarah4Charu5
One tray per mark. Each sheet goes on the tray its mark names

The pile now reads Esha, Ben, Dev, Anu, Farah, Charu, in order of marks. No two sheets were compared. The mark itself said where each sheet goes, as a value picks its slot in a count array. Every sort in this lesson uses that idea: the value is the index.

2 Counting sort: count, then write out

For plain numbers, a tray does not need to hold the sheets. One 3 looks like another, so a tray only needs to know how many landed on it. That is the count array from the counting lesson: count[v] holds how many values equal v.

Counting sort works in two passes:

  1. Count. For each value v, add 1 to count[v].
  2. Write out. Walk v from the smallest value to the largest, and write v down count[v] times.
Counting sort on the six marks
102102231405
count[v]: how many scored v
012345
Pass 1 counts. Nothing is written yet

Pass 2 never compares two values. It walks the slots in order, and the slots are already in the order of the values.

Marks start at 0, so mark v lives in slot v. Real arrays can hold negative values. So the code finds the smallest value, minValue, and keeps value v in slot v − minValue. The array needs one slot per value from the smallest to the largest. That number is the range size, k = maxValue − minValue + 1.

For [3, 1, 4, 1, 0, 3] it returns [0, 1, 1, 3, 3, 4]. For [2, -3, 0, -3], minValue is −3, so −3 lives in slot 0 and 2 lives in slot 5. It returns [-3, -3, 0, 2].

3 Keeping the names: where each block starts

Pass 2 wrote numbers, not sheets. Writing "1, 1" loses who scored 1. To sort records, we must move whole records, as the trays did.

The sorted row is made of blocks, one per mark: the 0s, the 1s, the 3s, then the 4. If we know where each block starts, each sheet can go straight to its place.

The 3s start after every sheet that scored less than 3. That is 1 + 2 + 0 = 3 sheets, so the 3s start at slot 3. Each mark's start is the total of the counts before it. This is the prefix array from the prefix sums lesson. start[0] is its leading 0, and each next start adds one more count:

start[v] = start[v−1] + count[v−1]
102102231405
count[v]: sheets with mark v
001132335465
start[v]: sheets with a mark below v
0123450s1s3s4s
The sorted row before any sheet is placed. Each shade is one mark's block

Nobody scored 2 or 5, so their blocks are empty. start[2] is 3, the same as start[3], because the 2s take no room.

4 Placing each sheet, left to right

We read the sheets in roll order. For each sheet:

  1. Its slot is start of its mark.
  2. The sheet goes into that slot.
  3. start of its mark goes up by 1, so the next sheet with that mark lands one slot further on.
Placing the sheets in roll order
3Anu1Ben4Charu1Dev0Esha3Farahi
Sheets in roll order
3Anu place
Anu's 3: start[3] is 3, then becomes 4

The same run as a table. place is the slot each sheet goes to:

isheetmarkplacestart after
[0, 1, 3, 3, 5, 6]
0Anu33[0, 1, 3, 4, 5, 6]
1Ben11[0, 2, 3, 4, 5, 6]
2Charu45[0, 2, 3, 4, 6, 6]
3Dev12[0, 3, 3, 4, 6, 6]
4Esha00[1, 3, 3, 4, 6, 6]
5Farah34[1, 3, 3, 5, 6, 6]

Ben and Dev both scored 1. Ben comes first in roll order, so he takes the first slot of the 1s block, and Dev takes the next one. A sheet always lands after the earlier sheets with the same mark. So this counting sort is stable: ties keep the order they came in.

The code moves indexes instead of sheets. order[place] = i means the sheet at index i goes to place.

For our marks it returns [4, 1, 3, 0, 5, 2]: Esha, Ben, Dev, Anu, Farah, Charu.

5 Cost, and when the range is too wide

  • Time: O(n + k). Counting and placing are one pass each over the n values. Building start, or writing out, is one pass over the k slots.
  • Space: O(k) for the counts, plus O(n) for the sorted row.

When k is not much bigger than n, that is O(n), which beats n log n. Sorting 10⁵ marks from 0 to 100 takes around 2 × 10⁵ steps.

A wide range breaks it, as it breaks a count array. Values up to 10⁹ need 10⁹ slots, about 4 GB of memory, even for ten values. Then the number of different values decides:

  • Few different values. Count them in a map, sort only the different keys, and write each key out as many times as its count.
  • Many different values. Use a comparison sort, O(n log n).

6 Bucket sort: one tray per range

The next test is marked out of 100. A tray per mark would mean 101 trays for eight sheets. So the teacher uses five trays, each for 20 marks: 0 to 19, 20 to 39, and so on. Mark m goes on tray m / 20, rounded down, so a 45 goes on tray 2.

Each tray holds only a few sheets, in no order yet. She sorts each tray by hand, then collects the trays in order. This is bucket sort, and each tray is a bucket.

45019188242363475916507
Eight marks out of 100
Bucket sort with trays 20 marks wide
01971245425036348891
Step 1: each mark goes on tray mark / 20. Tray 2 holds 40 to 59

Collecting trays 0 to 4 gives [7, 19, 42, 45, 50, 63, 88, 91]. Every mark on tray 2 is below every mark on tray 3, so the trays never need merging.

Each bucket is small, so any sort works inside it. The code calls the library sort to stay short.

C++

sort inside each bucket. Any sort is fine here, because a bucket holds only a few values.

Collections.sort on each list. A bucket is a List<Integer>, because the number of values in each one is not known in advance.

bucket.sort() sorts in place. [[] for _ in range(...)] makes a separate list per bucket. [[]] * bucket_count would make one list shared by every bucket.

Pass a compare function. sort() with no arguments compares values as text, so [19, 7] stays [19, 7]. sort((a, b) => a - b) compares them as numbers.

slices.Sort sorts in place. It needs import "slices". Each bucket starts as a nil slice, and append grows it.

sort on each bucket. The loop takes each bucket by value, so it needs mut to sort it before moving it into result.

List.Sort on each bucket. A bucket is a List<int>, because the number of values in each one is not known in advance.

The cost depends on how the values spread:

  • Spread out: about O(n) on average. With about n buckets over evenly spread values, each bucket holds one or two values.
  • Bunched together: the inner sort's cost. If every mark falls between 40 and 59, one bucket holds all n, and bucket sort costs as much as sorting it: O(n²) with insertion sort.
  • Space: O(n) for the buckets and the result.

The textbook version sorts n fractions from 0 to 1 into n buckets, with x in bucket ⌊x × n⌋.

7 Mistakes and edge cases

  • One slot short. Marks from 0 to 5 need 6 slots, so the size is maxValue - minValue + 1. Trays too: marks up to 100 in trays 20 wide need 6 trays, because 100 / 20 is 5.
  • No shift for negative values. Without the shift, the −3 in [2, -3, 0, -3] asks for slot −3. That is a Runtime Error or a quiet wrong answer, depending on the language.
  • Placing from the right. With start positions, the walk must go left to right. Walking from Farah back to Anu puts Dev before Ben, so the sort is no longer stable.
  • A range that overflows. With values from −2 × 10⁹ to 2 × 10⁹, maxValue - minValue is 4 × 10⁹, past a 32-bit int. That range is far too wide for counting sort anyway.

8 When to sort without comparing

The sign is in the constraints: the values are whole numbers in a small range, or they spread evenly over a known one.

  • Small range, plain numbers. Marks, ages, letters, or values up to about 10⁶: counting sort, O(n + k).
  • Records by a small key, ties in order. The stable version with start positions.
  • Values spread evenly over a known range. Bucket sort.
  • Counts as the key. A count lies between 1 and n, so buckets indexed by count group values by how often they appear, in O(n). This is the fast way into Top K Frequent Elements and Sort Characters By Frequency.
  • Wide or unknown range. A comparison sort. Sort an Array allows any 32-bit value, so its k is about 4 × 10⁹. Counting sort is out there, and merge sort is the way.

Radix sort builds on the stable version. It runs counting sort once per digit, last digit first, and stability keeps the order the earlier passes set.

Before sorting, read the value range in the constraints. A small range means the values can be indexes, and the sort never has to compare two of them.

Practice it

Finished this lesson?

Mark it read and it is ticked on the roadmap and in the list.

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.