Cardinal Sort (LSD)

Source: Internet
Author: User

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)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.