对int数组采用低位优先排序

该博客介绍了一种针对不同长度的十进制整数数组的排序算法,可以在O(N + K)的时间复杂度内完成,其中K是所有整数的总位数。通过将数字转换为32位int类型,并按照位进行低位优先排序,实现了高效排序。博客提供了一个名为`Sort`的方法,使用辅助数组`aux`,并遍历32位进行计数、分类和回写操作。此外,还包含一个辅助方法`bitAt`用于获取给定位的值。在main方法中,博主用随机生成的整数数组测试了该排序算法。

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

/*Given an array of N decimal integers of different lengths, 
describe how to sort them in O(N + K) time, 
where K is the total number of digits overall all the N integers. */

//将十进制数字转为int类型的值。int固定为32位。所以可以按照位进行低位优先的排序
public class Exercise3 {
	private static int R = 2;//二进制只要2个符号
	private static int[] aux; //辅助数组

	private static void Sort(int[] a) {
		if(a.length < 2) return;
		aux = new int[a.length];
		
		for(int w=0;w<32;w++){
			
			int[] count = new int[R+1];
			
			//计算频率
			for(int i=0;i<a.length;i++)
				count[bitAt(a[i],w)+1]++;
			
			//将频率转化为索引,因为只有0和1,所以可以免去计算
			
			//分类
			for(int i=0;i<a.length;i++){
				aux[count[bitAt(a[i],w)]++] = a[i];
			}
			
			//回写
			for(int i=0;i<a.length;i++)
				a[i] = aux[i];
		}
	}

	//取得一个bit位
	private static int bitAt(int num, int w) {
		int rs = num & ((int)1 << w);
		
		//判断符号位,是负数的时候要反过来,否则负数会排到正数后
		if(w == 31) return rs<0? 0:1; 
		else return rs>0? 1:0;
	}
	
	public static void main(String[] args) {
		int[] nums = new int[15];
		for(int i=0;i<nums.length;i++){
			nums[i] = (int)(Math.random()*100-50);
		}
			
		Sort(nums);
		
		for(int e : nums)
			System.out.println(e);
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值