C++ Online Compiler
Example: Counting Sort Implementation in C++
C
C++
C#
Java
Python
PHP
main.cpp
STDIN
Run
// Counting Sort Implementation #include <iostream> #include <vector> #include <algorithm> // Required for std::max_element using namespace std; void countingSort(vector<int>& arr) { if (arr.empty()) { return; // Nothing to sort } // Step 1: Find the maximum element in the input array // This determines the size of the count array. int max_val = *max_element(arr.begin(), arr.end()); // Step 2: Create a count array to store frequency of each element // The size of count_array will be max_val + 1 to accommodate 0 to max_val. vector<int> count(max_val + 1, 0); // Step 3: Populate the count array // count[i] will store the number of occurrences of i in arr. for (int x : arr) { count[x]++; } // Step 4: Modify the count array to store cumulative counts // count[i] will now store the number of elements less than or equal to i. for (int i = 1; i <= max_val; i++) { count[i] += count[i - 1]; } // Step 5: Create an output array to store the sorted elements // This array will have the same size as the input array. vector<int> output(arr.size()); // Step 6: Iterate through the input array from right to left // Place each element into its correct sorted position in the output array. // Decrement the count for that element to handle duplicates correctly. for (int i = arr.size() - 1; i >= 0; i--) { // The correct position for arr[i] is count[arr[i]] - 1 output[count[arr[i]] - 1] = arr[i]; count[arr[i]]--; // Decrement count for stability and duplicate handling } // Step 7: Copy the sorted elements from the output array back to the original array arr = output; } int main() { // Step 1: Initialize an unsorted array vector<int> arr = {4, 2, 2, 8, 3, 3, 1}; cout << "Original array: "; for (int x : arr) { cout << x << " "; } cout << endl; // Step 2: Call the countingSort function countingSort(arr); cout << "Sorted array: "; for (int x : arr) { cout << x << " "; } cout << endl; // Example with another array vector<int> arr2 = {10, 4, 1, 4, 2, 10, 7}; cout << "\nOriginal array 2: "; for (int x : arr2) { cout << x << " "; } cout << endl; countingSort(arr2); cout << "Sorted array 2: "; for (int x : arr2) { cout << x << " "; } cout << endl; return 0; }
Output
Clear
ADVERTISEMENTS