计数排序

本文详细介绍了一种简单且高效的排序算法——计数排序。通过使用额外的计数数组来记录源数组中每个数值出现的频率,并根据这些频率创建有序数组。文章深入浅出地解释了计数排序的工作原理,包括初始化计数数组、转换计数数组为索引数组以及构建最终的排序数组等步骤。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

计数排序有一个source数组,一个count数组,一个sorted数组,count数组是可以表示source最小数 min 到最大数 max 的范围。

遍历source在count中记录对应数出现的次数。count[souce[i] - min]++

将count数据转换为对应数据应该出现的位置。count[i] += count[i - 1]

遍历source并在count获取排序位置,放入sorted中对应位置。sorted[--count[source[i] - min]] = source[i];

@Override
	public int[] sort(int[] source) {
		int max = source[SortUtils.maxIndex(source)];
		int min = source[SortUtils.minIndex(source)];
		int[] count = getCountArr(source, max, min);
		LOG.d(count);
		count = changeCountArrToIndex(count);
		LOG.d(count);
		return makeSortedArr(source, count, min);
	}

	private int[] getCountArr(int[] source, int max, int min){
		int countSize = max - min + 1;
		int[] count = new int[countSize];
		for (int i = 0; i < source.length; i++){
			count[source[i] - min]++;
		}
		return count;
	}
	
	private int[] changeCountArrToIndex(int[] count){
		for (int i = 1; i < count.length; i++){
			count[i] += count[i - 1];
		}
		return count;
	}
	
	private int[] makeSortedArr(int[] source, int[] count, int min){
		int[] sorted = new int[source.length];
		for (int i = 0; i < source.length; i++){
			sorted[--count[source[i] - min]] = source[i];
		}
		return sorted;
	}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值