Reading history

Counting Sort and Radix Sort in C

5 min read 1 views

Learn counting sort and LSD radix sort in C: linear-time sorting of integers, stability, digit-by-digit passes, complexity and when to use them.

Comparison sorts such as merge sort and quick sort can never beat O(n log n) in the worst case, because they learn about the data only by comparing pairs of elements. When the values are integers in a limited range, you can do better by not comparing at all. Counting sort tallies how many times each value appears, and radix sort applies that idea one digit at a time. Both run in linear time for suitable data.

In this lesson you will learn

  • How counting sort works in three passes
  • Why placing elements from the back keeps the sort stable
  • LSD radix sort digit by digit
  • Time and space complexity of both
  • When non-comparison sorts are the right choice

Compare these with the basic sorts and merge sort.

Counting Sort

#include <stdio.h>
#include <string.h>

/* Counting sort for values in the range 0..max (stable version) */
void counting_sort(const int *in, int *out, int n, int max) {
    int count[101];
    memset(count, 0, sizeof count);
    for (int i = 0; i < n; i++) count[in[i]]++;              /* 1. count each value */
    for (int v = 1; v <= max; v++) count[v] += count[v - 1]; /* 2. running totals = end positions */
    for (int i = n - 1; i >= 0; i--)                         /* 3. place from the back: stable */
        out[--count[in[i]]] = in[i];
}

int main(void) {
    int marks[] = {7, 3, 9, 3, 0, 10, 7, 5, 3, 8};          /* quiz marks out of 10 */
    int n = 10, sorted[10];
    counting_sort(marks, sorted, n, 10);
    printf("Before: ");
    for (int i = 0; i < n; i++) printf("%d ", marks[i]);
    printf("\nAfter : ");
    for (int i = 0; i < n; i++) printf("%d ", sorted[i]);
    printf("\n");
    return 0;
}

Output

Before: 7 3 9 3 0 10 7 5 3 8 
After : 0 3 3 3 5 7 7 8 9 10
  • Pass 1 counts each value: count[3] becomes 3 because three students scored 3.
  • Pass 2 turns the counts into running totals. Now count[v] is the position just after the last place where v belongs.
  • Pass 3 walks the input from the back and places each value at --count[v]. Going backwards keeps equal values in their original order, making the sort stable, which radix sort depends on.
  • The time is O(n + k), where k is the range of values (here 0 to 10). Extra space is the count array plus the output array.

Radix Sort

#include <stdio.h>
#include <string.h>

/* LSD radix sort: counting sort on each decimal digit, ones place first */
static void sort_by_digit(int *a, int n, int exp) {
    int out[32], count[10];
    memset(count, 0, sizeof count);
    for (int i = 0; i < n; i++) count[(a[i] / exp) % 10]++;
    for (int d = 1; d < 10; d++) count[d] += count[d - 1];
    for (int i = n - 1; i >= 0; i--) out[--count[(a[i] / exp) % 10]] = a[i];
    memcpy(a, out, n * sizeof a[0]);
}

void radix_sort(int *a, int n) {
    int max = a[0];
    for (int i = 1; i < n; i++) if (a[i] > max) max = a[i];
    for (int exp = 1; max / exp > 0; exp *= 10) {
        sort_by_digit(a, n, exp);
        printf("after digit %-4d: ", exp);
        for (int i = 0; i < n; i++) printf("%d ", a[i]);
        printf("\n");
    }
}

int main(void) {
    int a[] = {170, 45, 75, 90, 802, 24, 2, 66};
    radix_sort(a, 8);
    return 0;
}

Output

after digit 1   : 170 90 802 2 24 45 75 66 
after digit 10  : 802 2 24 45 66 170 75 90 
after digit 100 : 2 24 45 66 75 90 170 802
  • LSD (least significant digit) radix sort runs a stable counting sort on the ones digit, then the tens, then the hundreds.
  • (a[i] / exp) % 10 extracts the current digit; exp is 1, 10, 100 and so on, until it exceeds the largest number.
  • After the ones pass, numbers are ordered by their last digit (170 and 90 end in 0, 802 and 2 in 2). Each later pass keeps that order among equal digits, so after the final pass the list is fully sorted.
  • With d digits and base 10, the time is O(d × (n + 10)). For fixed-width keys such as 32-bit integers or phone numbers, that is linear in n.

Comparison

AlgorithmTimeExtra spaceStableWorks on
Merge sortO(n log n)O(n)YesAnything comparable
Quick sortO(n log n) averageO(log n)NoAnything comparable
Counting sortO(n + k)O(n + k)YesSmall integer ranges
Radix sortO(d × (n + b))O(n + b)YesIntegers, fixed-length strings

k is the value range, d the number of digits and b the base. Counting sort is a poor choice when the range is huge compared with n, for example sorting 10 numbers between 0 and one billion.

Common Mistakes

  1. Negative numbers: shift values by subtracting the minimum before counting, then add it back.
  2. Placing elements from the front in pass 3, which breaks stability and therefore radix sort.
  3. Running radix sort from the most significant digit with the LSD code; MSD radix sort needs a different, recursive design.
  4. Allocating a count array for a huge range, wasting memory.

Practice Exercises

Exercise 1. Adapt counting sort to handle values from -5 to 5.

Show answer
int min = -5, range = 11;           /* 5 - (-5) + 1 */
/* use count[a[i] - min] everywhere instead of count[a[i]] */
for (int i = 0; i < n; i++) count[a[i] - min]++;
for (int v = 1; v < range; v++) count[v] += count[v - 1];
for (int i = n - 1; i >= 0; i--) out[--count[a[i] - min]] = a[i];

Exercise 2. How many passes does radix sort need for the numbers 5, 1234 and 99?

Show answer

4 passes, one for each digit of the largest number, 1234. Shorter numbers are treated as having leading zeros.

Frequently Asked Questions

If radix sort is linear, why is quick sort used more often?

Radix sort needs extra memory, only works on keys that can be split into digits, and its constant factors are higher. For general data and moderate sizes, a well-tuned comparison sort is usually faster in practice.

What does stable mean?

A stable sort keeps items with equal keys in their original relative order. If students are sorted by name and then stably by grade, students with the same grade stay in alphabetical order.

Summary

  • Counting sort counts values, builds running totals and places items in O(n + k).
  • Placing from the back makes it stable.
  • Radix sort applies stable counting sort to each digit, ones place first.
  • Both beat O(n log n) when keys are small integers or fixed-width.

Next: KMP String Matching in C.

Lessons are also marked complete when you click Next.

Leave a Reply

Your email address will not be published. Required fields are marked *