Sort Algorithm series: Count sorting (Counting sort) (C language)

Source: Internet
Author: User

Common Understanding: by establishing a connection between the array to be sorted and the sub-mark of the secondary array, the secondary array stores the number of each element of the original array equal to its own subscript, then, perform some operations to ensure the stability of counting sorting (you may not understand it well enough. Please submit your opinion ). Watch the dynamic process
[Cpp]
Int count_sort (int * const array, const int size)
{
Int * count;
Int * temp;
Int min, max;
Int range, I;

Min = max = array [0];
For (I = 0; I <size; I ++)
{
If (array [I] <min)
Min = array [I];
Else if (array [I]> max)
Max = array [I];
}
Range = max-min + 1;
Count = (int *) malloc (sizeof (int) * range );
If (NULL = count)
Return 0;
Temp = (int *) malloc (sizeof (int) * size );
If (NULL = temp)
{
Free (count );
Return 0;
}
For (I = 0; I <range; I ++)
Count [I] = 0;
For (I = 0; I <size; I ++)
Count [array [I]-min] ++; // records the number of values equal to the array subscript
For (I = 1; I <range; I ++)
Count [I] + = count [I-1]; // store the subscript value of your array at the position corresponding to the target array to ensure stability
For (I = size-1; I> = 0; I --)
Temp [-- count [array [I]-min] = array [I]; // store the original array in size order to another array
For (I = 0; I <size; I ++)
Array [I] = temp [I];
Free (count );
Free (temp );

Return 1;
}

The running time is bytes (n + k)

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.