2025年01月13日 建站教程
public void bucketSort(int[] nums){
int max = Integer.MIN_VALUE;
int min = Integer.MAX_VALUE;
for(int num : nums){
max = Math.max(max, num);
min = Math.min(min, num);
}
int bucketCount = (max-min)/nums.length+1;
List<List<Integer>> bucketList = new ArrayList<>();
for (int i = 0; i < bucketCount; i++) {
bucketList.add(new ArrayList<>());
}
for(int num : nums){
int index = (num-min)/nums.length;
bucketList.get(index).add(num);
}
for(List<Integer> bucket : bucketList){
Collections.sort(bucket);
}
int j = 0;
for(List<Integer> bucket : bucketList){
for(int num : bucket){
nums[j] = num;
j++;
}
}
}
PS:类似计数排序,不同点在于统计的是某个区间(桶)里的数。
本文链接:http://so.lmcjl.com/news/21253/