/**
* 计数排序
* 对于一个输入数组中的一个元素x,
* 只要我们知道了这个数组中比x小的元素的个数,
* 那么我们就可以直接把x放到(x+1)的位置上。这就是计数排序的基本思想
*/
@Test
public void countSort(){
int[] array = {1,4,5,6,7,9,5,6,3,2};
countSort(array,10);
System.out.println(Arrays.toString(array));
}
public void countSort(int[] array,int k){
//初始化count数组
int[] count = new int[k];
for (int item:array){
count[item]++;
}
for (int i=1;i<k;i++){
count[i]=count[i]+count[i-1];
}
int[] b = new int[array.length];
for (int j=array.length-1;j>=0;j--){
b[count[array[j]]-1] = array[j];
count[array[j]]--;
}
System.arraycopy(b,0,array,0,array.length);
}