|
| 1 | +#include <iostream> |
| 2 | +#include <algorithm> |
| 3 | +#include <cmath> |
| 4 | +using namespace std; |
| 5 | + |
| 6 | +/* |
| 7 | +Counting sort implementation for sorting given array. |
| 8 | +Note - Works on Non-negative integer array only. |
| 9 | +
|
| 10 | +Parameters: |
| 11 | +int a[] - Integer array a to be sorted. |
| 12 | +int n - size of array a. |
| 13 | +int r. - Range of numbers in a. |
| 14 | +*/ |
| 15 | + |
| 16 | +void counting_sort(int a[], int n, int r) { |
| 17 | + if(a == NULL) return; |
| 18 | + |
| 19 | + int *cnt = new int[r+1]; //array to store count of each occurences |
| 20 | + int *out = new int[n]; //Out array to store sorted values |
| 21 | + |
| 22 | + |
| 23 | + // Intitialise the count array to 0 |
| 24 | + for (int i = 0; i <= r; ++i) |
| 25 | + cnt[i] = 0; |
| 26 | + |
| 27 | + // Count each occurences digit wise |
| 28 | + for (int i = 0; i < n; ++i) |
| 29 | + cnt[a[i]]++; |
| 30 | + |
| 31 | + // Cumulative count array |
| 32 | + for (int i = 1; i <= r; ++i) |
| 33 | + cnt[i]+=cnt[i-1]; |
| 34 | + |
| 35 | + // Sort |
| 36 | + for (int i = n - 1; i >= 0; i--) { |
| 37 | + // Note - starting from n-1 to maintain "stable sort" property |
| 38 | + out[cnt[a[i]] - 1] = a[i]; |
| 39 | + cnt[a[i]]--; |
| 40 | + } |
| 41 | + |
| 42 | + // Copy results back to orignal array |
| 43 | + for (int i = 0; i < n; i++) |
| 44 | + a[i] = out[i]; |
| 45 | +} |
| 46 | + |
| 47 | + |
| 48 | +int main() { |
| 49 | + ios_base::sync_with_stdio(false); //For faster io |
| 50 | + int a[] = {1, 2, 9, 293, 41, 15, 52, 3, 121, 7, 1223, 3449, 15, 1 }; |
| 51 | + int n = sizeof(a)/sizeof(a[0]); |
| 52 | + |
| 53 | + // Get the iterator to max element for calculating range of number |
| 54 | + int * max_a_itr = max_element(a, a+n); |
| 55 | + int max_a = *max_a_itr; |
| 56 | + |
| 57 | + |
| 58 | + cout << "Input Array:\n"; |
| 59 | + for (int i = 0; i < n; i++) { |
| 60 | + cout << a[i] << " "; |
| 61 | + } |
| 62 | + cout << "\n"; |
| 63 | + |
| 64 | + counting_sort(a, n, max_a); |
| 65 | + |
| 66 | + cout << "Sorted Array:\n"; |
| 67 | + for (int i = 0; i < n; i++) { |
| 68 | + cout << a[i] << " "; |
| 69 | + } |
| 70 | + cout << "\n"; |
| 71 | + |
| 72 | + return 0; |
| 73 | +} |
0 commit comments