视频讲解地址:【手把手带你写十大排序】8.桶排序(Java语言)_哔哩哔哩_bilibili
代码:
public class BucketSort {public void sortFunction(int[] array, int bucketNum) {int max = Integer.MIN_VALUE, min = Integer.MAX_VALUE;for (int i : array) {max = Math.max(max, i);min = Math.min(min, i);}List<List<Integer>> bucketList = new ArrayList<List<Integer>>();for (int i = 0; i < bucketNum; i++) {bucketList.add(new ArrayList<Integer>());}for (int i : array) {int bucketIndex = (i - min) * (bucketNum - 1) / (max - min);List<Integer> list = bucketList.get(bucketIndex);list.add(i);}for (int i = 0, arrIndex = 0; i < bucketList.size(); i++) {List<Integer> bucket = bucketList.get(i);Collections.sort(bucket);for (int num : bucket) {array[arrIndex++] = num;}}}
}