The count sort is a linear sort.
Sort Ascending:
Public void Sortbyasc (int[] data) {if (data = = NULL | | data.length <= 1) return;/** find the range of data */int rang E = data[0];for (int i = 1; i< data.length; i++) {if (range < Data[i]) {range = Data[i];}} if (range <= 0) { Syst Em.out.println ("The boundary cannot be negative"); return; } /** count Sort */countsortbyasc (Data,range);} private void Countsortbyasc (int[] data, int range) {/** constructs a range+1-length array countarray, with each element initially set to 0 (the default in Java is 0). */int[] Countarray = new Int[range + 1];/** traverse the array to be sorted, calculating the number of occurrences of each element, such as a key I element appears 3 times, then countarray[i]=3. */for (int i = 0;i < Data.length; i++) {int val = data[i];if (val < 0 | | val > Range) {System.out.println ("Subscript hyper-bounds");
return;} Countarray[val] + = 1;} for (int i = 0,index = 0;i < Countarray.length, i++) {for (int j = 0; J <countarray[i];j++) {Data[index] = i;index++;} }}
Sort Descending:
Public void Sortbydesc (int[] data) {if (data = = NULL | | data.length <= 1) return;/** find the range of data */int ran GE = data[0];for (int i = 1; i< data.length; i++) {if (range < Data[i]) {range = Data[i];}} if (range <= 0) { Sys Tem.out.println ("The boundary cannot be negative"); return; } /** count Sort */countsortbydesc (Data,range);} private void Countsortbydesc (int[] data, int range) {/** constructs a range+1-length array countarray, with each element initially set to 0 (the default in Java is 0). */int[] Countarray = new Int[range + 1];/** traverse the array to be sorted, calculating the number of occurrences of each element, such as a key I element appears 3 times, then countarray[i]=3. */for (int i = 0;i < Data.length; i++) {int val = data[i];if (val < 0 | | val > Range) {System.out.println ("Subscript hyper-bounds");
return;} Countarray[val] + = 1;} for (int i = Countarray.length-1,index = 0;i >=0, i--) {for (int j = 0; J <countarray[i];j++) {Data[index] = I;index ++;}}}
Basic sort Java Implementation (3)--count sort