Course offer · HLD · LLD · System Design at ₹799 until 30 Nov (not interview packs)

Counting Sort in C++

Sort small-range integers with counting sort in C++: count each value, turn counts into positions, and place items stably. Handles negatives by shifting.

IntermediateSorting & Searching ProgramsExample 8 of 13
counting-sort.cpp
1#include <iostream>
2#include <algorithm>
3#include <vector>
4using namespace std;
5
6void countingSort(int arr[], int n) {
7 int max = *max_element(arr, arr + n);
8 int min = *min_element(arr, arr + n);
9 int range = max - min + 1;
10
11 vector<int> count(range, 0);
12 int output[n];
13
14 // Store count of each element
15 for (int i = 0; i < n; i++)
16 count[arr[i] - min]++;
17
18 // Change count to position
19 for (int i = 1; i < range; i++)
20 count[i] += count[i - 1];
21
22 // Build output array
23 for (int i = n - 1; i >= 0; i--) {
24 output[count[arr[i] - min] - 1] = arr[i];
25 count[arr[i] - min]--;
26 }
27
28 // Copy output to original array
29 for (int i = 0; i < n; i++)
30 arr[i] = output[i];
31}
32
33void printArray(int arr[], int n) {
34 for (int i = 0; i < n; i++) {
35 cout << arr[i] << " ";
36 }
37 cout << endl;
38}
39
40int main() {
41 int arr[] = {4, 2, 2, 8, 3, 3, 1};
42 int n = sizeof(arr) / sizeof(arr[0]);
43
44 cout << "Original array: ";
45 printArray(arr, n);
46
47 countingSort(arr, n);
48
49 cout << "Sorted array: ";
50 printArray(arr, n);
51
52 return 0;
53}

Sample Output

Sorted array: 1 2 2 3 3 4 8

Values placed by count positions.

In this one

  • How counting occurrences replaces comparisons
  • How a prefix sum turns counts into end positions
  • How subtracting min supports negative numbers
  • Why vector<int> is used for the count array

How it works

  1. 1

    Find min (1) and max (8); range = 8.

  2. 2

    Count each value at index value − min.

  3. 3

    Prefix-sum the counts.

  4. 4

    Walk the input backwards, placing each value at count − 1.

  5. 5

    Copy output back.

Edge cases

Huge range

Sort {1, 1000000000}.

range is a billion, so the count vector needs gigabytes. Counting sort only suits small ranges.

Negative values

Sort {-2, 3, -1}.

Subtracting min (-2) maps -2 to index 0, so negatives work.

What's going on

The program sorts an array of integers using the Counting Sort algorithm. For example:

Input array: [4, 2, 2, 8, 3, 3, 1]
Output array: [1, 2, 2, 3, 3, 4, 8]

Counting Sort works by counting how many times each value appears, then placing each element in its correct position based on these counts.

Header Files Used

1.#include <iostream>
Provides cout and cin for input/output operations.
2.#include <algorithm>
Provides max_element() and min_element() functions to find range.

Understanding Counting Sort

Algorithm Concept:

Count occurrences of each value
Calculate cumulative counts (positions)
Place elements in correct positions
Stable sorting algorithm

Visual Example:

Array: [4, 2, 2, 8, 3, 3, 1]

Step 1: Count occurrences

Value 1: count = 1
Value 2: count = 2
Value 3: count = 2
Value 4: count = 1
Value 8: count = 1

Step 2: Calculate positions (cumulative counts)

Position for 1: 0
Position for 2: 1
Position for 3: 3
Position for 4: 5
Position for 8: 6

Step 3: Place elements

Result: [1, 2, 2, 3, 3, 4, 8]

Function: countingSort()

void countingSort(int arr[], int n) {

int max = *max_element(arr, arr + n);

int min = *min_element(arr, arr + n);

int range = max - min + 1;

int vector<int> count(range, 0);

int output[n];

// Store count of each element

for (int i = 0; i < n; i++)

count[arr[i] - min]++;

// Change count to position

for (int i = 1; i < range; i++)

count[i] += count[i - 1];

// Build output array

for (int i = n - 1; i >= 0; i--) {

output[count[arr[i] - min] - 1] = arr[i];

count[arr[i] - min]--;

}

// Copy output to original array

for (int i = 0; i < n; i++)

arr[i] = output[i];

}

How it works:

Finds min and max to determine range
Counts occurrences of each value
Converts counts to positions (cumulative)
Places elements in correct positions (right to left for stability)

Step-by-Step Algorithm

Step 1: Find Range

max = 8, min = 1
range = 8 - 1 + 1 = 8
Count array size: 8

Step 2: Count Occurrences

arr[i] - min: maps value to count array index
Example: 4 - 1 = 3 → count[3]++
Builds frequency array

Step 3: Calculate Positions

Cumulative sum: count[i] += count[i-1]
Each count[i] now represents starting position
Example: count[2] = 3 means value 3 starts at position 3

Step 4: Build Output

Process from right to left (for stability)
Place element at position count[arr[i] - min] - 1
Decrement count after placement

Understanding Count to Position Conversion

Before (counts):

count[0] = 1 (value 1 appears 1 time)

count[1] = 2 (value 2 appears 2 times)

count[2] = 2 (value 3 appears 2 times)

count[3] = 1 (value 4 appears 1 time)

count[7] = 1 (value 8 appears 1 time)

After (positions):

count[0] = 1 (value 1 at position 0)

count[1] = 3 (value 2 at positions 1-2)

count[2] = 5 (value 3 at positions 3-4)

count[3] = 6 (value 4 at position 5)

count[7] = 7 (value 8 at position 6)

Time and Space Complexity

Time Complexity: O(n + k)

n: number of elements
k: range of values (max - min + 1)
Counting: O(n)
Position calculation: O(k)
Building output: O(n)
Total: O(n + k)

Space Complexity: O(n + k)

Output array: O(n)
Count array: O(k)
Total: O(n + k)

Stability: Stable

Processing from right to left maintains relative order
Equal elements preserve their original order

When to Use Counting Sort

Best For:

Small range of integer values
When k is not much larger than n
When stability is required
Non-negative integers (or with offset)

Not Recommended For:

Large range (k >> n) - wastes space
Floating-point numbers
Strings or complex objects
When range is unknown or very large

Important Considerations

Range Calculation:

range = max - min + 1
Handles negative numbers with offset (arr[i] - min)
Count array size equals range

Stability:

Processing from right to left (i = n-1 to 0) ensures stability
Equal elements maintain relative order

Index Mapping:

arr[i] - min: maps value to count array index
Handles any range starting from min
Example: values 100-107 → indices 0-7

return 0;

This ends the program successfully.

A note on the count array: an earlier listing declared it as int count[range] = {0};. Because range is only known at run time, that is a variable-length array, and Clang rejects initializing one with = {0}. The code now uses vector<int> count(range, 0);, which is standard C++, starts every slot at zero, and lives on the heap, so a large range does not overflow the stack.

Quiz

Tap an option. The answer stays hidden until you pick.

Question 1

After counting {4,2,2,8,3,3,1} with min 1, count[1] holds:

Pick an answer to check it.

Question 2

When is counting sort a poor choice?

Pick an answer to check it.

Questions people ask

Time complexity?

O(n + range).

Why walk the input backwards?

To keep equal values in their original order, which keeps the sort stable.

Is output still a VLA?

Yes, int output[n] remains a compiler extension; vector<int> output(n) would make it fully standard.