Understanding of counting sequencing and implementation of code

Source: Internet
Author: User

The decision tree model shows that the next term to compare the worst cases is to compare the NLGN times, not the linear sort. So, in the introduction of the algorithm, several linear sorts are proposed, in which the counting sort is one kind. The following summarizes the principle of counting sorting:

Assume that each element in N input elements is an integer within [0,.., K]. Set the input array to a[n]; the output array is b[n]; The temporary storage array is c[k]. The algorithm is as follows:

1. Place all elements in C[k] 0.

2. Statistics A contains the number of element I (i={0,..., k-1}) and is stored in c[i].

3. Count the number of elements in a that are less than or equal to i (i={0,..., k-1}) and stored in c[i].

4. Starting with n-1, the position specified in B, which is equal to the element of I in A, B is a well-ordered output. Because in 2 and 3 we already know the number of elements that are less than or equal to I, so here we just need to store I on B[c[i] [], and subtract the c[i] by 1, repeating this process until all the elements in a are stored in B.

The C language is implemented as follows:

#include <stdio.h> #include <stdlib.h> #include <time.h>void countsort (int a[],int b[],int n,int k) {    int i,*c;    C=malloc (k*sizeof (int));    for (i=0;i<k;i++) c[i]=0;     for (i=0;i<n;i++) c[a[i]]++;    Count the number of a[i in the array a], and place the a[i] value in C[a[i]].  for (i=1;i<k;i++) c[i]+=c[i-1];    Calculate how much of a is less than or equal to A[i], and store it in C[a[i]].  for (i=n;i>0;i--) b[--c[a[i-1]]]=a[i-1];    Store the value of a[i-1] in B[--c[a[i-1]]]. Free (C);}


This article is from the "stupid Donkey on the tree" blog, please be sure to keep this source http://xu2015.blog.51cto.com/10019822/1675911

Understanding and code implementation of counting sorting

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