Created
October 8, 2019 12:47
-
-
Save belushkin/2003990e0034ff7b513ea8cb34af298b to your computer and use it in GitHub Desktop.
Counting sort correct implementation but NOT from memory
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <bits/stdc++.h> | |
int a[] = {9,3,1,4,5,7,7,2,2}; | |
void counting_sort(int a[], int n) { | |
int radix = *std::max_element(a, a + n); | |
int c[radix+1] = {}; | |
int b[n] = {}; | |
for (int i = 0; i < n; i++) { | |
c[a[i]]++; | |
} | |
for (int j = 1; j <= radix; j++) { | |
c[j] = c[j] + c[j-1]; | |
} | |
for (int m = n-1; m > -1; m--) { | |
int d = a[m]; | |
c[d]--; | |
b[c[d]] = a[m]; | |
} | |
for (int i = 0; i < n; i++) { | |
a[i] = b[i]; | |
} | |
} | |
int main() { | |
int n = sizeof(a)/sizeof(a[0]); | |
counting_sort(a, n); | |
for (int i = 0; i<n; i++) { | |
std::cout << a[i] << " "; | |
} | |
std::cout << "\n"; | |
return 1; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment