AlgoTales · Roadmap

Counting sort

Intermediate · 8 min · code in PHP, JavaScript, Java and Go

Where you will meet this in real life

Counting sort does not compare items at all. When values come from a small range, such as marks from 0 to 100, it counts how many times each value appears and rebuilds the sorted list from those counts. It is extremely fast for that kind of data.

Practical use cases

  • Web app: Ranking 10 lakh exam scores. A results portal must rank 10 lakh students whose marks are whole numbers from 0 to 100. It keeps 101 counters, adds one for each student, and then reads the counters in order. Ranking finishes in a blink instead of the long wait a general sort would need.
  • Web app: Sorting reviews by star rating. A review site lists reviews by rating from 1 to 5 stars. With only five possible values, counting how many reviews fall into each and then laying them out in order is quick, even with millions of reviews. The page shows lists grouped by stars right away.
  • System: Helper inside radix sort. Counting sort is the building block of radix sort, which sorts long numbers digit by digit. Each digit has only ten possible values, so ten counters are enough per pass, and large numbers can be sorted without ever comparing two whole values.

The story: Zoya and the Star Slips

Zoya's family ran a small kirana store, and customers dropped feedback slips into a box, each with one to four stars. At the end of the month there were hundreds of slips, and her father wanted them sorted from fewest stars to most.

Zoya started the usual way: comparing two slips, swapping, comparing again. It was slow and tiring. Then she noticed something: there are only four possible values. Why compare at all?

She laid out four trays labelled 1, 2, 3 and 4 stars. She read each slip once and dropped a tally mark in its tray. After one pass she knew: "one 1-star, two 2-star, one 3-star, three 4-star". Writing the sorted list was then trivial: say "1" once, "2" twice, and so on.

Her father was amazed. "You never compared two slips!" Right: that is counting sort. It is wonderfully quick when the range of values is small, like ages, ratings, or marks out of 10.

How to spot this problem, and where you need it

You have a huge list of whole numbers that all fall in a small range, such as ages, marks or ratings, and a general sort feels wasteful.

Signs you need it

  • The values are whole numbers or categories from a small, known range, such as 0 to 100, 1 to 5 or A to Z.
  • You have lakhs of items but only a few dozen different values.
  • The problem says "sort numbers in range", "ranks by marks" or "frequency of each value" with a small limit.

Where to use it in a project

  • Ranking students by marks, grouping people by age, or ordering reviews by star rating.
  • Sorting letters, small codes or status values in large datasets.

The solution

Make an array of counters, one per possible value, all starting at zero. Walk through the data once and add one to the counter of each value you see. Then walk through the counters in order and write each value out as many times as its counter says. To keep equal items in their original order, turn the counters into running totals and place items from the back.

Payoff: Before: comparing 10 lakh scores many times over. After: two simple passes and 101 counters, finishing almost instantly.

Explain it like I am 8

You have a pile of crayons in four colours. Instead of comparing crayons, put four cups on the table and drop each crayon into its colour cup. Then empty the cups one after another: all reds, then all blues. Done!

How it works, step by step

  1. Find the smallest and biggest value so you know the range.
  2. Make a tally array with one counter per possible value, all zero.
  3. Go through the input once, adding 1 to the counter of each value you see.
  4. Walk through the counters from smallest value to biggest, and write each value out as many times as its counter says.
  5. Use it when the range of values is small compared with the number of items.

The code in four languages

PHP

<?php
// Counting sort: tally every value, then write the values back in order.
function countingSort(array $a): array {
    if (!$a) return [];
    $min = min($a);
    $max = max($a);
    $counts = array_fill(0, $max - $min + 1, 0);   // one tally box per possible value
    foreach ($a as $v) {
        $counts[$v - $min]++;                      // drop a tally mark
    }
    $out = [];
    foreach ($counts as $i => $c) {
        for ($k = 0; $k < $c; $k++) {
            $out[] = $i + $min;                    // write the value c times
        }
    }
    return $out;
}
echo implode(', ', countingSort([3, 1, 4, 2, 4, 2, 4]));   // 1, 2, 2, 3, 4, 4, 4

JavaScript

// Counting sort: tally every value, then write the values back in order.
function countingSort(a) {
  if (a.length === 0) return [];
  const min = Math.min(...a);
  const max = Math.max(...a);
  const counts = new Array(max - min + 1).fill(0);   // one tally box per possible value
  for (const v of a) {
    counts[v - min]++;                               // drop a tally mark
  }
  const out = [];
  counts.forEach((c, i) => {
    for (let k = 0; k < c; k++) out.push(i + min);   // write the value c times
  });
  return out;
}
console.log(countingSort([3, 1, 4, 2, 4, 2, 4]).join(', '));   // 1, 2, 2, 3, 4, 4, 4

Java

import java.util.*;
import java.util.stream.*;

public class Main {
    // Counting sort: tally every value, then write the values back in order.
    static int[] countingSort(int[] a) {
        if (a.length == 0) return new int[0];
        int min = Arrays.stream(a).min().getAsInt();
        int max = Arrays.stream(a).max().getAsInt();
        int[] counts = new int[max - min + 1];     // one tally box per possible value
        for (int v : a) {
            counts[v - min]++;                     // drop a tally mark
        }
        int[] out = new int[a.length];
        int pos = 0;
        for (int i = 0; i < counts.length; i++) {
            for (int k = 0; k < counts[i]; k++) {
                out[pos++] = i + min;              // write the value counts[i] times
            }
        }
        return out;
    }

    // Joins the numbers with a separator, e.g. "1, 2, 3".
    static String join(int[] a, String sep) {
        return Arrays.stream(a).mapToObj(String::valueOf).collect(Collectors.joining(sep));
    }

    public static void main(String[] args) {
        System.out.println(join(countingSort(new int[]{3, 1, 4, 2, 4, 2, 4}), ", "));   // 1, 2, 2, 3, 4, 4, 4
    }
}

Go

package main

import (
	"fmt"
	"strconv"
	"strings"
)

// Counting sort: tally every value, then write the values back in order.
func countingSort(a []int) []int {
	if len(a) == 0 {
		return []int{}
	}
	min, max := a[0], a[0]
	for _, v := range a {
		if v < min {
			min = v
		}
		if v > max {
			max = v
		}
	}
	counts := make([]int, max-min+1) // one tally box per possible value
	for _, v := range a {
		counts[v-min]++ // drop a tally mark
	}
	out := []int{}
	for i, c := range counts {
		for k := 0; k < c; k++ {
			out = append(out, i+min) // write the value c times
		}
	}
	return out
}

// join glues the numbers together with a separator, e.g. "1, 2, 3".
func join(a []int, sep string) string {
	parts := make([]string, len(a))
	for i, v := range a {
		parts[i] = strconv.Itoa(v)
	}
	return strings.Join(parts, sep)
}

func main() {
	fmt.Println(join(countingSort([]int{3, 1, 4, 2, 4, 2, 4}), ", ")) // 1, 2, 2, 3, 4, 4, 4
}

Time: O(n + k) · Extra space: O(k). n is the number of items and k is how many different values are possible. Great when k is small, terrible when k is huge (like sorting a few phone numbers).

Watch out for

  • Using it on huge ranges such as 10-digit phone numbers. The tally array would be enormous.
  • Forgetting the minimum offset, which breaks on negative numbers or values that do not start at 0.
  • Using it on decimals or words directly. It needs whole numbers (or something you can turn into one).

Quick check

  1. What does counting sort do instead of comparing items?
    • Counts how many times each value appears
    • Swaps neighbours
    • Splits the list in half
  2. Which data suits counting sort best?
    • A million 10-digit numbers
    • A million names
    • A million exam marks from 0 to 100
  3. What do n and k mean in O(n + k)?
    • n is the item count, k is the range of values
    • n is the range, k is the item count
    • Both are item counts