桶排序

桶排序不是基于比较的排序算法,最快的效率可以达到 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;
	}
	
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值