Example code:
#include <iostream> #include <cstdio>using namespace std;//radix sort (LSD) from the lowest bit to the highest level for such allocations to collect void print (int a[], int n) {for (int t=0; t<n; ++t) {if (t+1<n) {printf ("%d", a[t]);} else {printf ("%d\n", A[t]);}}} int caldigit (int num, int d) {int a[3] = {1, ten, 100};return num/a[d]%10;} void Radixsort (int a[], int begin, int end) {int count[10]; A total of 10 barrels int len = End-begin+1;int *p = (int*) malloc ((end-begin+1) *sizeof (int)); for (int i=0; i<3; ++i)//A total of 3 digits, from the low open Start {for (int t=0; t<10; ++t) {count[t] = 0;} for (int t=begin; t<=end; ++t) {count[caldigit (a[t], i)]++;} for (int t=1; t<10; ++t) {count[t] + = count[t-1];} for (int t=end; t>=begin;--t)//from rear to front, guaranteeing stability of cardinal sort {int pos = CalDigit (a[t], i); Which is the first bucket p[count[pos]-1] = a[t];count[pos]--;} for (int t=0; t<len; ++t) {A[t+begin] = p[t];}} Free (p); return;} int main () {int a[] = {4, 2, 7, 312, 412, 143, 689};p rintf ("before sorting: \ n");p rint (A, 8);p rintf ("after sorting: \ n"), Radixsort (A, 0, +);p Rint (A, 8); return 0;}
Operation Result:
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Cardinal Sort (LSD)