Algorithm memorizing-sorting series-counting sorting

Source: Internet
Author: User

1. Brief Introduction

The sorting object of counting sorting is generally an integer.
Assume that the array to be sorted is int array [] and the array length is n.
Step 1: traverse the array to obtain the maximum value max and minimum value min of the array. (N)
Step 2: open a new array, int count []. The array length is max-min + 1, and each element is initialized to 0.
Step 3: traverse the array and count the number of each element in the array in the count array. (N)
Step 4: Fill the array according to the Count array. (N + k)

2. Complexity

Assume that the range of values in the array is K, where k = max-min + 1, the time complexity is O (n + k). In fact, this complexity is the time complexity of step 4, in the four steps, the number of elements traversed should be n + N + k = 3 * n + K.
The space complexity is O (k). When the value range in the array is large, a large extra space is used. For data types such as char, counting sorting is still very useful.
Stability is a stable sorting.

3. Code

Void counting_sort (int array [], int n ){
// Obtain the value range.
Int max = array [0];
Int min = array [0];
For (int I = 1; I <n; I ++ ){
If (array [I]> max)
Max = array [I];
Else if (array [I] <min)
Min = array [I];
}
// Open up the auxiliary space
Int range = max-min + 1;
Int * count = new int [range];
For (int I = 0; I <range; I ++)
Count [I] = 0;
// Counting process
For (int I = 0; I <n; I ++)
Count [array [I]-min] ++;
// Reverse Filling
Int index = 0; // subscript of array
For (int I = min; I <= max & index <n; I ++) // traverses each value
For (int j = 0; j <count [I-min] & index <n; j ++) // Number of times each value appears
Array [index ++] = I;
Delete [] count;
}

4. References

Wikipedia-count sorting http://en.wikipedia.org/wiki/Counting_sort

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.