8-2. Counting sort

Source: Internet
Author: User

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

Related Keywords:

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.