LOGBOOK

HELP

Quiz Entry - updated: 2026.11.27

How does bucket-sort sort $n$ entries whose keys are integers in $[0, N-1]$?

It uses each key as an index into an array $B$ of $N$ initially empty sequences, the buckets. Phase 1 moves every entry $(k, o)$ to the end of bucket $B[k]$; phase 2 goes through $B[0], B[1], \ldots, B[N-1]$ in order and appends each bucket's entries to the output. No two keys are ever compared.

Bucket-sort of (7,d) (1,c) (3,a) (7,g) (3,b) (7,e) with ten buckets: entries hang below buckets 1, 3 and 7, then are collected in index order

* Phase 1 distributes the entries by key; phase 2 collects the buckets from left to right. *

Algorithm bucketSort(S, N)
  B ← array of N empty sequences
  while ¬S.isEmpty()                       // phase 1: distribute
    (k, o) ← S.remove(S.first())
    B[k].insertLast((k, o))
  for i ← 0 to N − 1                       // phase 2: collect
    while ¬B[i].isEmpty()
      (k, o) ← B[i].remove(B[i].first())
      S.insertLast((k, o))

The sorting happens by position: bucket $B[3]$ comes before $B[7]$ in the array, so everything with key 3 is collected before everything with key 7. In the example only the keys 1, 3 and 7 occur; the other seven buckets stay empty and add nothing in phase 2.

An entry $(k, o)$ is a key with an attached value: the key decides the order, the value travels along, like a student record behind its grade or a task behind its priority. The letters in the example make it visible that $(3,a)$ and $(3,b)$ come out in the order they went in, which is what makes bucket-sort stable.

Go deeper:

From Quiz: ADS / Sorting Lower Bound, Bucket-Sort and Radix-Sort | Updated: Nov 27, 2026