DSA
    intermediate

    Counting Sort

    Counting Sort

    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.

    ⏱ O(n+k)
    💾 O(n+k)
    Ready
    1. Count
    2. Cumulative
    3. Output
    Input Array
    4
    2
    2
    8
    3
    3
    1
    Count Array (index = value)
    0
    0
    1
    0
    2
    0
    3
    0
    4
    0
    5
    0
    6
    0
    7
    0
    8
    0
    Output Array (Sorted)
    -
    -
    -
    -
    -
    -
    -

    Initialize count array with zeros

    50%
    Live Variables
    max8
    count.length9

    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

    Test your knowledge

    20 questions
    Question 1 of 20
    Score: 0

    When is Counting Sort most efficient?

    The short version

    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!

    In more depth

    Three Phases

    1. Count Phase: Count occurrences of each value

    2. Cumulative Phase: Convert counts to positions

    3. Output Phase: Place elements in correct positions

    Stability

    Iterating backwards during output phase ensures stability (equal elements maintain relative order).

    Limitations

    Only works for discrete values (integers)
    Space increases with range (k)
    Not suitable when k >> n

    When to reach for this

    • Values are integers in a known, limited range
    • Need linear O(n) sorting
    • Sorting characters, grades, or small integers
    • As a subroutine in Radix Sort

    Interview Questions

    Amazon
    Twitter
    Google
    Facebook
    LinkedIn
    Apple
    Google
    Bloomberg

    Love this visualization?

    Sign up to track your progress, earn achievements, use the AI assistant, and access your personal learning dashboard.

    100% free • No credit card required