桶排序不是基于比较的排序算法,最快的效率可以达到 O(n)。但是是很费空间的一种排序算法。
将数据按一定原则分桶,如 10,29,18,38 按 n/10分桶,那么可分为 0:[], 1:[10,18], 2:[29], 3:[38] 四桶。
然后在对桶中的数据单独排序(如在新增数据的时候作插入排序),极限情况下,一个桶中只有一个数据那么时间复杂度就是O(n)了。
// 桶中只存相同的值,并没有进行分段,所以不用对桶内数据排序。
// 一般情况是数据分段,然后对桶内数据排序(后者直接在填满桶的时候进行插入排序)
public class BucketSort implements Sort {
@Override
public int[] sort(int[] source) {
int max = source[SortUtils.maxIndex(source)];
int min = source[SortUtils.minIndex(source)];
int bucketSize = max - min + 1;
List<List<Integer>> bucket = new ArrayList<>(bucketSize);
bucket = initBucket(bucket, bucketSize);
bucket = fullBucket(bucket, bucketSize, min, source);
int[] result = sortInBucket(bucket, source);
return result;
}
public List<List<Integer>> initBucket(List<List<Integer>> bucket, int n){
for (int i = 0; i < n; i++){
bucket.add(new ArrayList<Integer>());
}
return bucket;
}
public List<List<Integer>> fullBucket(List<List<Integer>> bucket, int bucketSize, int bucketMin, int[] source){
for (int i = 0; i < source.length; i++){
int bucketNum = source[i] - bucketMin;
bucket.get(bucketNum).add(source[i]);
}
return bucket;
}
public int[] sortInBucket(List<List<Integer>> bucket, int[] source){
int[] result = new int[source.length];
int rIndex = 0;
for (List<Integer> list : bucket){
for (int i : list){
result[rIndex++] = i;
}
}
return result;
}
}