十大排序算法之桶排序
设置一个定量的数组当作空桶;
遍历输入数据,并且把数据一个一个放到对应的桶里去;
对每个不是空的桶进行排序;
从不是空的桶里把排好序的数据拼接起来。
这里给出一份Java的代码实现:
public class BucketSorted {
public void bucketSort(int[] a) {
if (a.length == 0) {
return ;
}
int i, sortedIndex = 0;
int minValue = Integer.MAX_VALUE;
int maxValue = Integer.MIN_VALUE;
for (i = 0; i < a.length; i++) {
minValue = Math.min(minValue, a[i]);
maxValue = Math.max(maxValue, a[i]);
}
int bucketCount = (maxValue - minValue) / a.length + 1;
ArrayList<ArrayList<Integer>> buckets = new ArrayList<>(bucketCount);
for (i = 0; i < bucketCount; i++) {
buckets.add(new ArrayList<>());
}
for (i = 0; i < a.length; i++) {
buckets.get((a[i] - minValue) / a.length).add(a[i]);
}
for (i = 0; i < bucketCount; i++) {
ArrayList<Integer> bucket = buckets.get(i);
Collections.sort(bucket);
for (i = 0; i < bucket.size(); i++) {
a[sortedIndex ++] = bucket.get(i);
}
}
}
}