IntermediateAbout 20 min

    Counting Sort

    Read the full article on Substack

    7 min read.

    A non-comparison sorting algorithm that achieves O(n+k) time by counting occurrences. Perfect when the range of values (k) is not significantly larger than n.

    Think of it this way: Imagine sorting a deck of cards by suit. Instead of comparing cards, you count how many of each suit you have, then deal them out in order. No comparisons needed!

    input40212283343516
    count000102030405060708
    output0123456

    Values range 0..8, so make 9 counters. No comparisons at all.

    1/24

    Check your understanding

    Answer from memory before you scroll back up. Pulling an idea out of your head is what makes it stay there.

    Sort without comparing

    Sequence

    Order the steps of a stable counting sort.

    Tap a piece, then tap where it goes — or drag it. Tap the tray to take one back.

    1. 1Drop a step here
    2. 2Drop a step here
    3. 3Drop a step here
    4. 4Drop a step here
    5. 5Drop a step here
    5 pieces left to place

    Quiz

    20 questions
    Question 1 of 20
    Score: 0

    When is Counting Sort most efficient?

    Done with this lesson?

    Sign in free to keep your progress, streak and quiz scores.

    Keep going