Counting Sort
Counting Sort Algorithm in C++ (Complete Implementation)
IntermediateTopic: Sorting & Searching Programs
C++ Counting Sort Program
This program helps you to learn the fundamental structure and syntax of C++ programming.
#include <iostream>
#include <algorithm>
using namespace std;
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 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];
}
void printArray(int arr[], int n) {
for (int i = 0; i < n; i++) {
cout << arr[i] << " ";
}
cout << endl;
}
int main() {
int arr[] = {4, 2, 2, 8, 3, 3, 1};
int n = sizeof(arr) / sizeof(arr[0]);
cout << "Original array: ";
printArray(arr, n);
countingSort(arr, n);
cout << "Sorted array: ";
printArray(arr, n);
return 0;
}Output
Original array: 4 2 2 8 3 3 1 Sorted array: 1 2 2 3 3 4 8
Understanding Counting Sort
Counting Sort is a non-comparative sorting algorithm that sorts integers by counting occurrences of each value. Time Complexity: O(n + k) where k is range. Space Complexity: O(n + k). It's stable and efficient when the range of input data is not significantly greater than the number of elements.
Note: To write and run C++ programs, you need to set up the local environment on your computer. Refer to the complete article Setting up C++ Development Environment. If you do not want to set up the local environment on your computer, you can also use online IDE to write and run your C++ programs.