Directory (?) [+] Introduction to counting sorting algorithm
The comparison sorting algorithm can be proved by the decision tree model, its off-line is O (NLGN). And this article is about the time efficiency of O (n) of the counting sort . The so-called sorting algorithm, is to put the right elements in the correct position, counting is to calculate the same key elements of the number of each, and then according to the number of occurrences of the cumulative to obtain the final position information. But the counting sort has two restrictions, that is, the existence of a positive integer k, so that all the elements in the array key value is not more than n, and the key value is a nonnegative integer. Java implementation of counting sort algorithm
Counting sort algorithm steps have three steps: Build an array of length k+1 C, where each element is initially set to 0 (Java inside default is 0). Iterate over the array to be sorted, calculating the number of occurrences of each element, such as 3 occurrences of a key element I, then c[i]=3. Add a C array, get the element's rank, start traversing C, c[i+1]=c[i]+c[i-1 from 0, and build a temporary array T, which is the same length as the array to be sorted. From the end of the array traversing the array to be sorted, the elements are arranged into T, directly from the C inside can get the exact location of the elements, but remember each processing an element after the corresponding position in C minus 1.
The exact sort and test code is as follows:[Java] View plain copy public class countsort { public static void main (String[] args) throws exception { int[] array = { 9, 8, 7, 6, 5, 4, 3, 2, 6, 1, 0 }; system.out.println (" Before sort: "); Arrayutils.printarray (array); countsort (array, 9); system.out.println ("After sort:"); &Nbsp; arrayutils.printarray (array); } public static Void countsort (int[] array, int range) throws Exception { if (range <= 0) { Throw new exception ("Range can ' T be negative or zero."); } if (array.length <= 1) { return; } int[] countarray = new int[range + 1]; for ( int i = 0; i < array.length; i++) { int value = array [i]; if (value < 0 | | value > range) { throw new exception ("array Element overflow range. "); } countArray[value] += 1; } for (int i = 1; i < countarray.length; i++) { countArray[i] += countArray[i - 1]; } int[] temp = new int[ array.length]; for ( int i = array.length - 1; i >= 0; i--) { int value = array[i]; int position = countarray[value] - 1; temp[position] = value; countarray[value] -= 1; } for (int i = 0; i < array.length; i++) { array[i] = temp[i]; } } }