Typorithm · medium

Counting Sort

▷ Interactive algorithm labcounting-sortsortingdistributioncountingnon-comparison
Saved on this device
Full lesson · 8 learning steps Open any exercise for focused practice
1

Step 1 of 8 · intro card

Learn Counting Sort

0%

Sorting Algorithms

Counting Sort counts integer frequencies, then rebuilds the array by walking values in order.

Counting Sort is not comparison-based; it uses values as indexes.

The counts array needs a known, limited value range from 0 through maxValue.

The first pass counts how often each value appears.

The second pass walks the counts array from low to high and emits each value the counted number of times.

It can run in O(n + k), where k is the value range size.

Preparing algorithm lab…
01

Works best for small integer ranges.

02

Use counts[value] to store frequency.

03

Walk the counts array in numeric order.

04

Runtime is O(n + k).

05

This simple version returns a new result array.

function countingSort(arr, maxValue) {
  const counts = Array(maxValue + 1).fill(0);

  for (const value of arr) {
    counts[value]++;
  }

  const result = [];

  for (let value = 0; value < counts.length; value++) {
    while (counts[value] > 0) {
      result.push(value);
      counts[value]--;
    }
  }

  return result;
}

Read the implementation

Connect each part of the code to the concept before you type.

1. Count table

Create one counter for every integer from 0 through maxValue.

const counts = Array(maxValue + 1).fill(0)

2. Count input

Scan the input and count how often each value appears.

for (const value of arr)

3. Increment count

The value itself is used as an index into the counts array.

counts[value]++

4. Output array

This version writes sorted values into a new result array.

const result = []

5. Walk values

Walking counts from low to high produces ascending order.

for (let value = 0; value < counts.length; value++)

6. Emit repeats

Repeated values are pushed once for each count.

while (counts[value] > 0)

7. Push value

Push the current value into the sorted output.

result.push(value)

8. Use one count

Decrease the count after emitting one copy.

counts[value]--

A complete learning loop

01

Understand

Read the concept map and follow the code breakdown.

02

Reconstruct

Type the implementation, repair mistakes and work through every recall exercise.

03

Verify

Use the final check without hints; revisit weak concepts in short practice sessions.

Counting Sort: Visual Walkthrough & Practice · Typorithm | ApplyDjinn