The key to counting sorting is how to handle the final position of each element. In the count order, we can maintain an array c[i] to record the position of the element where the key value is I. Each time you enter a a[i], first record the number of occurrences of each a[i] c[i], and then c[i]=c[i-1]+c[i] from the front, so that the value is the position of the last number of repetitions in the new array after sorting. One obvious problem with counting sorting is the problem of determining the size of the c[] array. The following is the code I understand to write.
#include <iostream>using namespace Std;int main () {int n,i;int a[1000],b[1000],c[1000];while (cin>>n) {for ( i=1;i<=n;i++) cin>>a[i];for (i=0;i<=n;i++) c[i]=0;for (i=1;i<=n;i++) c[a[i]]=c[a[i]]+1;for (i=1;i< =n;i++) c[i]=c[i-1]+c[i];for (i=1;i<=n;i++) {b[c[a[i]]]=a[i]; C[a[i]]-=1;} for (i=1;i<=n;i++) cout<<b[i]<< ""; Cout<<endl;} return 0;}
Algorithmic Introduction to counting sorting