C++ Online Compiler
Example: Radix Sort Implementation in C++
C
C++
C#
Java
Python
PHP
main.cpp
STDIN
Run
// Radix Sort Implementation #include <iostream> #include <vector> #include <algorithm> // Required for std::max_element // Function to get the maximum value from an array int getMax(const std::vector<int>& arr) { int maxVal = arr[0]; for (size_t i = 1; i < arr.size(); ++i) { if (arr[i] > maxVal) { maxVal = arr[i]; } } return maxVal; } // A function to do counting sort of arr[] according to // the digit represented by exp. void countingSort(std::vector<int>& arr, int exp) { int n = arr.size(); std::vector<int> output(n); // Output array std::vector<int> count(10, 0); // Count array for digits 0-9 // Store count of occurrences in count[] for (int i = 0; i < n; ++i) { count[(arr[i] / exp) % 10]++; } // Change count[i] so that count[i] now contains actual // position of this digit in output[] for (int i = 1; i < 10; ++i) { count[i] += count[i - 1]; } // Build the output array // Iterate from right to left to ensure stability for (int i = n - 1; i >= 0; --i) { output[count[(arr[i] / exp) % 10] - 1] = arr[i]; count[(arr[i] / exp) % 10]--; } // Copy the output array to arr[], so that arr[] now // contains sorted numbers according to current digit for (int i = 0; i < n; ++i) { arr[i] = output[i]; } } // The main function to that sorts arr[] of size n using Radix Sort void radixSort(std::vector<int>& arr) { // Find the maximum number to know number of digits int m = getMax(arr); // Do counting sort for every digit. Note that exp is 10^i // where i is current digit number for (int exp = 1; m / exp > 0; exp *= 10) { countingSort(arr, exp); } } int main() { // Step 1: Initialize an array of integers std::vector<int> arr = {170, 45, 75, 90, 802, 24, 2, 66}; std::cout << "Original array: "; for (int x : arr) { std::cout << x << " "; } std::cout << std::endl; // Step 2: Call Radix Sort to sort the array radixSort(arr); // Step 3: Print the sorted array std::cout << "Sorted array: "; for (int x : arr) { std::cout << x << " "; } std::cout << std::endl; // Test with another array std::vector<int> arr2 = {329, 457, 657, 839, 436, 720, 355}; std::cout << "\nOriginal array 2: "; for (int x : arr2) { std::cout << x << " "; } std::cout << std::endl; radixSort(arr2); std::cout << "Sorted array 2: "; for (int x : arr2) { std::cout << x << " "; } std::cout << std::endl; return 0; }
Output
Clear
ADVERTISEMENTS