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.
1#include <iostream>2#include <algorithm>3#include <vector>4using namespace std;56void 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;1011 vector<int> count(range, 0);12 int output[n];1314 // Store count of each element15 for (int i = 0; i < n; i++)16 count[arr[i] - min]++;1718 // Change count to position19 for (int i = 1; i < range; i++)20 count[i] += count[i - 1];2122 // Build output array23 for (int i = n - 1; i >= 0; i--) {24 output[count[arr[i] - min] - 1] = arr[i];25 count[arr[i] - min]--;26 }2728 // Copy output to original array29 for (int i = 0; i < n; i++)30 arr[i] = output[i];31}3233void printArray(int arr[], int n) {34 for (int i = 0; i < n; i++) {35 cout << arr[i] << " ";36 }37 cout << endl;38}3940int main() {41 int arr[] = {4, 2, 2, 8, 3, 3, 1};42 int n = sizeof(arr) / sizeof(arr[0]);4344 cout << "Original array: ";45 printArray(arr, n);4647 countingSort(arr, n);4849 cout << "Sorted array: ";50 printArray(arr, n);5152 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
Find min (1) and max (8); range = 8.
- 2
Count each value at index value − min.
- 3
Prefix-sum the counts.
- 4
Walk the input backwards, placing each value at count − 1.
- 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:
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
Understanding Counting Sort
Algorithm Concept:
Visual Example:
Array: [4, 2, 2, 8, 3, 3, 1]
Step 1: Count occurrences
Step 2: Calculate positions (cumulative counts)
Step 3: Place elements
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:
Step-by-Step Algorithm
Step 1: Find Range
Step 2: Count Occurrences
Step 3: Calculate Positions
Step 4: Build Output
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)
Space Complexity: O(n + k)
Stability: Stable
When to Use Counting Sort
Best For:
Not Recommended For:
Important Considerations
Range Calculation:
Stability:
Index Mapping:
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.