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