|
| 1 | +// C++ implementation of Radix Sort |
| 2 | + |
| 3 | +#include <iostream> |
| 4 | +using namespace std; |
| 5 | + |
| 6 | +// A utility function to get maximum value in arr[] |
| 7 | +int getMax(int arr[], int n) |
| 8 | +{ |
| 9 | + int mx = arr[0]; |
| 10 | + for (int i = 1; i < n; i++) |
| 11 | + if (arr[i] > mx) |
| 12 | + mx = arr[i]; |
| 13 | + return mx; |
| 14 | +} |
| 15 | + |
| 16 | +// A function to do counting sort of arr[] according to |
| 17 | +// the digit represented by exp. |
| 18 | +void countSort(int arr[], int n, int exp) |
| 19 | +{ |
| 20 | + int output[n]; // output array |
| 21 | + int i, count[10] = { 0 }; |
| 22 | + |
| 23 | + // Store count of occurrences in count[] |
| 24 | + for (i = 0; i < n; i++) |
| 25 | + count[(arr[i] / exp) % 10]++; |
| 26 | + |
| 27 | + // Change count[i] so that count[i] now contains actual |
| 28 | + // position of this digit in output[] |
| 29 | + for (i = 1; i < 10; i++) |
| 30 | + count[i] += count[i - 1]; |
| 31 | + |
| 32 | + // Build the output array |
| 33 | + for (i = n - 1; i >= 0; i--) { |
| 34 | + output[count[(arr[i] / exp) % 10] - 1] = arr[i]; |
| 35 | + count[(arr[i] / exp) % 10]--; |
| 36 | + } |
| 37 | + |
| 38 | + // Copy the output array to arr[], so that arr[] now |
| 39 | + // contains sorted numbers according to current digit |
| 40 | + for (i = 0; i < n; i++) |
| 41 | + arr[i] = output[i]; |
| 42 | +} |
| 43 | + |
| 44 | +// The main function to that sorts arr[] of size n using |
| 45 | +// Radix Sort |
| 46 | +void radixsort(int arr[], int n) |
| 47 | +{ |
| 48 | + // Find the maximum number to know number of digits |
| 49 | + int m = getMax(arr, n); |
| 50 | + |
| 51 | + // Do counting sort for every digit. Note that instead |
| 52 | + // of passing digit number, exp is passed. exp is 10^i |
| 53 | + // where i is current digit number |
| 54 | + for (int exp = 1; m / exp > 0; exp *= 10) |
| 55 | + countSort(arr, n, exp); |
| 56 | +} |
| 57 | + |
| 58 | +// A utility function to print an array |
| 59 | +void print(int arr[], int n) |
| 60 | +{ |
| 61 | + for (int i = 0; i < n; i++) |
| 62 | + cout << arr[i] << " "; |
| 63 | +} |
| 64 | + |
| 65 | +// Driver Code |
| 66 | +int main() |
| 67 | +{ |
| 68 | + int arr[] = { 170, 45, 75, 90, 802, 24, 2, 66 }; |
| 69 | + int n = sizeof(arr) / sizeof(arr[0]); |
| 70 | + |
| 71 | + // Function Call |
| 72 | + radixsort(arr, n); |
| 73 | + print(arr, n); |
| 74 | + return 0; |
| 75 | +} |
0 commit comments