publicstaticint[] countSort(int[] array){ int max = array[0]; int min = array[0]; for(int i = 0; i < array.length; i++){ if (array[i] > max) max = array[i]; if (array[i] < min) min = array[i]; } int d = max -min;
//填写统计数组 int[] countArray = newint [d+1]; for(int i = 0; i < array.length; i++) countArray[array[i] - min]++;
//统计数组变形 for(int i = 1; i < countArray.length; i++) countArray[i] += countArray[i-1];
publicstaticdouble[] bucketSort(double[] array){ double max = array[0]; double min = array[0]; for(int i = 1; i < array.length; i++){ if (array[i] > max) max = array[i]; if (array[i] < min) min = array[i]; } double d = max - min;
int bucketNum = 9; ArrayList<LinkedList <Double>> bucketList = new ArrayList<LinkedList <Double>>(bucketNum); for(int i = 0; i < bucketNum; i++) bucketList.add(new LinkedList<Double> ());
for(int i = 0; i < array.length; i++){ int num = (int)((array[i] - min)*(bucketNum-1)/d); bucketList.get(num).add(array[i]); }
for(int i = 0; i < bucketList.size(); i++) //JDK底层采用了归并排序或归并的优化版本 Collections.sort(bucketList.get(i));
double[] sortedArray = newdouble[array.length]; int index = 0; //增强版的for只能遍历,不能修改值 for(LinkedList<Double> list : bucketList) { for (double element : list) { sortedArray[index++] = element; } } return sortedArray; }