The basic idea of counting sorting is: to count the number of a number in a sequence that is less than an element a is n, place the element a directly in the n+1 position. Of course, when there are several elements to make the appropriate adjustments, because all the elements can not be placed in the same position. The count sort assumes that the input elements are integers between 0 and K .
8-2. Count sort. cpp: The entry point that defines the console application. #include "stdafx.h" #include <iostream>using namespace std;void countsort (int a[],int b[],int array_size,int k) { int* c=new int[k+1];for (int i=0;i<=k;i++) {c[i]=0;} C[i] contains the number of elements equal to IFOR (int i=0;i<array_size;i++) {c[a[i]]++;} C[i] contains the number of elements less than or equal to IFOR (int i=1;i<=k;i++) {c[i]=c[i]+c[i-1];} Confirm the NUM positionfor (int i=array_size-1;i>=0;i--) {b[c[a[i]]-1]=a[i];c[a[i]]--;}} int _tmain (int argc, _tchar* argv[]) {int a[8]={2,5,3,0,2,3,0,3};int b[8]; Countsort (a,b,8,5); for (int i=0;i<8;i++) {cout<<b[i]<< "";} Cout<<endl;return 0;}
For data 2 5 3 0 2 3 0 3 The procedure is performed as shown in:
Now there is a problem, if it has to be 0 to n natural numbers, is not the use of small? I think, actually can be arbitrary integer, that is, to find the smallest number to see with 0 of the distance d, all the number minus D, row to 0 to N in the range, count sort. It's up to the end to be restored.
8-2. Counting sort