1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
|
int main()
{
int A[] = {2, 9, 5, 7, 8, 5, 10, 4};
const int SIZE = sizeof(A)/sizeof(A[0]); // get SIZE of array
int B[SIZE] = {};
int k = *std::max_element(A, A + SIZE) + 1;
countingSort(A, B, SIZE, k);
for(int i : B) std::cout << i << " ";
std::cout << "\n";
}
void countingSort(int A[], int B[], int SIZE, int k)
{
int C[k];
for(int i = 0; i < k; i++)
C[i] = 0;
for(int j = 0; j < SIZE; j++)
C[A[j]]++;
for(int i = 1; i < k ; i++)
C[i] += C[i-1];
for(int j = SIZE-1; j >= 0; j--)
B[ C[A[j]]-- ] = A[j]; // post-decrement
}
|