/*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 & ((in
对int数组采用低位优先排序
最新推荐文章于 2023-03-17 10:32:43 发布