Sorting Algorithm-count sorting (C ++)

Source: Internet
Author: User
/*************************************** * ************ Array: * array that to be sorted. * nlength: * length of array * NK: * maximum number that may appear (nk = 9 for a 10-digit number ). **************************************** * **********/void countingsort (INT array [], size_t nlength, int NK) {If (null = array | 0 = nlength | 0 = NK) return; int * COUNT = new int [NK + 1]; memset (count, 0, sizeof (INT) * (NK + 1); int * arrayresult = new int [nlength]; memset (arrayresult, 0, sizeof (INT) * nlength); // count first. Count [idx] is the number of elements whose value is equal to idx. For (INT idx = 0; idx <nlength; idx ++) count [array [idx] ++; // accumulate again. Count [idx] is the number of elements less than or equal to idx for (INT idx = 1; idx <NK + 1; idx ++) Count [idx] = count [idx] + Count [idx-1]; // round-robin From the back to the front (ensuring stable sorting ), sort array [idx] into all the numbers smaller than or equal to array [idx] (count [array [idx] in total) the back of for (INT idx = nLength-1; idx> = 0; idx --) {arrayresult [count [array [idx]-1] = array [idx]; count [array [idx] --;} memcpy (array, arrayresult, sizeof (INT) * nlength); Delete [] count; Delete [] arrayresult ;}

Related Article

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: 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.