publicstaticint[]CountingSort(int[] array){if(array.length ==0)return array;int bias, min = array[0], max = array[0];for(int i =1; i < array.length; i++){if(array[i]> max)
max = array[i];if(array[i]< min)
min = array[i];}
bias =0- min;int[] bucket =newint[max - min +1];Arrays.fill(bucket,0);for(int i =0; i < array.length; i++){
bucket[array[i]+ bias]++;}int index =0, i =0;while(index < array.length){if(bucket[i]!=0){
array[index]= i - bias;
bucket[i]--;
index++;}else
i++;}return array;}
基数排序
publicstaticint[]RadixSort(int[] array){if(array ==null|| array.length <2)return array;// 1.先算出最大数的位数;int max = array[0];for(int i =1; i < array.length; i++){
max =Math.max(max, array[i]);}int maxDigit =0;while(max !=0){
max /=10;
maxDigit++;}int mod =10, div =1;ArrayList<ArrayList<Integer>> bucketList =newArrayList<ArrayList<Integer>>();for(int i =0; i <10; i++)
bucketList.add(newArrayList<Integer>());for(int i =0; i < maxDigit; i++, mod *=10, div *=10){for(int j =0; j < array.length; j++){int num =(array[j]% mod)/ div;
bucketList.get(num).add(array[j]);}int index =0;for(int j =0; j < bucketList.size(); j++){for(int k =0; k < bucketList.get(j).size(); k++)
array[index++]= bucketList.get(j).get(k);
bucketList.get(j).clear();}}return array;}
桶排序
publicstaticArrayList<Integer>BucketSort(ArrayList<Integer> array,int bucketSize){if(array ==null|| array.size()<2)return array;int max = array.get(0), min = array.get(0);// 找到最大值最小值for(int i =0; i < array.size(); i++){if(array.get(i)> max)
max = array.get(i);if(array.get(i)< min)
min = array.get(i);}int bucketCount =(max - min)/ bucketSize +1;ArrayList<ArrayList<Integer>> bucketArr =newArrayList<>(bucketCount);ArrayList<Integer> resultArr =newArrayList<>();for(int i =0; i < bucketCount; i++){
bucketArr.add(newArrayList<Integer>());}for(int i =0; i < array.size(); i++){
bucketArr.get((array.get(i)- min)/ bucketSize).add(array.get(i));}for(int i =0; i < bucketCount; i++){if(bucketSize ==1){// 如果带排序数组中有重复数字时 感谢 @见风任然是风 朋友指出错误for(int j =0; j < bucketArr.get(i).size(); j++)
resultArr.add(bucketArr.get(i).get(j));}else{if(bucketCount ==1)
bucketSize--;ArrayList<Integer> temp =BucketSort(bucketArr.get(i), bucketSize);for(int j =0; j < temp.size(); j++)
resultArr.add(temp.get(j));}}return resultArr;}