十大排序算法之基数排序
取得数组中的最大数,并取得位数;
arr为原始数组,从最低位开始取每个位组成radix数组;
对radix进行计数排序(利用计数排序适用于小范围数的特点);
这里给出一份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);
}
}
}
}