C Counting Sort

Intermediate
6 min read
Updated: Nov 2026
1 example

Counting Instead of Comparing

Counting sort does not compare elements. It counts how many times each key occurs in a range 0..k, then writes the keys back in order. Time is O(n + k) and space is O(k), so it is ideal when keys are small non-negative integers and the range is not much larger than n. With a prefix-sum pass it can also be made stable.

Remember
int count[K + 1] = {0};
for (i...) count[a[i]]++;
for (v = 0, k = 0; v <= K; v++)
    for (c = count[v]; c > 0; c--) a[k++] = v;

Cheat Sheet

Keep these facts handy while you work with Counting Sort in C.

TopicDetail
TimeO(n + k)
SpaceO(k)
KeysSmall non-negative integers
ComparisonsNone

C Examples

Compile each example with gcc file.c -std=c11 -Wall -o out. Next: Bucket Sort.

Example 1 — Count then rebuild

Keys are in the range 0 to 9.

C
#include <stdio.h>

int main(void) {
    int a[] = {4, 2, 2, 8, 3, 3, 1};
    int n = 7, count[10] = {0};

    for (int i = 0; i < n; i++) count[a[i]]++;

    printf("counts:");
    for (int v = 0; v < 10; v++)
        if (count[v]) printf(" %d->%d", v, count[v]);

    int k = 0;
    for (int v = 0; v < 10; v++)
        for (int c = count[v]; c > 0; c--) a[k++] = v;

    printf("\nsorted:");
    for (int i = 0; i < n; i++) printf(" %d", a[i]);
    printf("\n");
    return 0;
}

How It Works

  1. The count array records how many times each value appears.
  2. Writing each value count[v] times rebuilds the array in order.
  3. No two elements are ever compared.

Edge Cases & Pitfalls

Check these before relying on Counting Sort in real programs.

range

Huge key range

If the maximum key is huge, count wastes memory and time.

neg

Negative keys

Offset keys by the minimum, or use another algorithm.

Key Takeaways

  • Count, then write back.
  • O(n + k).
  • Keys must be small integers.

One line: Counting sort does not compare elements.

Frequently Asked Questions

When keys are integers in a small known range, such as ages, grades, or characters.
No. It uses key values as indexes, so the O(n log n) comparison lower bound does not apply.
Continue with "C Bucket Sort" next. Spread values into range buckets, sort each bucket, and concatenate. The C Sorting Algorithms hub lists every topic in order.

Next: Bucket Sort

Spread values into range buckets, sort each bucket, and concatenate.

Continue →

CODETOFUN NEWS

Stay Ahead in Tech

Get the latest IT news, programming updates, and technology trends directly on your phone.

Your daily dose of tech, straight to your feed.

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

11 people found this page helpful