The base sort is not much to say, the idea is as follows:
0. Input is n integers, each digit is B-bit
1. Split integer into B/R "bit", each "bit" length is r (decimal length)
2. Sort each "bit" as a count from low to high
It is worth saying that, in order to make the algorithm most efficient, R should be LGN (rounding), but the implementation does not limit the size of R, can be set by itself.
Not much to say, on the code: (RadixSort.h omitted)
1. RadixSort.cpp
#include"stdafx.h"#include<malloc.h>#include<math.h>voidRadixsort (intA[],intLengthintDigitintminbit) { //int r = log2 ((double) length); intR =Minbit; intRange = POW (10.0, R); int* Bucket = (int*) malloc (range *sizeof(int)); int* Count = (int*) malloc (range *sizeof(int)); for(inti = R-1; i < digit; i + =r) {intModnum = POW (10.0, i +1); intLastmodnum = POW (10.0, i +1-R); for(intj =0; J < Range; J + +) {Count[j]=0; BUCKET[J]=0; } for(intK =0; K < length; k++) { if(I-r <0) {Count[a[k]% modnum]++; } Else { inttemp = (A[k]% modnum-a[k]% lastmodnum)/Lastmodnum; Count[temp]++; } } for(intj =1; J < Range; J + +) {Count[j]+ = Count[j-1]; } for(intK = Length-1; K >=0; k--) { if(I-r <0) {Bucket[count[a[k]% Modnum]-1] =A[k]; COUNT[A[K]% modnum]--; } Else { inttemp = (A[k]% modnum-a[k]% lastmodnum)/Lastmodnum; Bucket[count[temp]-1] =A[k]; Count[temp]--; } } for(intK =0; K < length; k++) {A[k]=Bucket[k]; } printf ("round%d\n", i); for(inti =0; i < length; i++) {printf ("%d\t", A[i]); } printf ("\ n"); }}
2. Main.cpp
//Main.cpp: Defines the entry point of the console application. //#include"stdafx.h"#include"RadixSort.h"int_tmain (intARGC, _tchar*argv[]) { intA[] = {4343,1212,5353,4141,8080,303,9999 }; intLength =sizeof(a)/sizeof(int); Radixsort (A, length,4,1); return 0;}
Although the algorithm or slag level, or to rely on a single-step debug code, or 0/1 of the subscript guilty confused, but can write such code, compared to the previous self is a huge victory!
Actually wrote the cardinal order without hurting my vitality--)