java实现一个bitmap--《编程珠玑ch1》


/**
 * 用于排序一个满足以下条件的文件:
 *      (1) 文件中只范围在0~1024*1024*8-1的整数
 *      (2) 每个数字只出现1次或0次
 * 使用到的数组大小:
 *      约1MB
 * 排序时间复杂度:
 *      O(n), n为文件中出现的数字总数
 */
public class BitMap {
    public static void main(String[] args){
        // 该位图大小约为1MB, 实际会比1MB大, 因为对象头还会占一些字节
        int[] bitmap = new int[256*1024];
        // 该数组中一共有多少个bit位就能表示多大的数
        int total = 32 * 256 * 1024;

        // 从0-total中选几个数插入到bitmap中, 这里可以替换为从文件读取
        for (int i=0;i<total;i++){
            // 每1024个就插入一个数, 当然也可以每512个或者完全随机(但需要保证每个数字最多出现一次)
            if ((i & 1023) == 0){
                put(bitmap, i);
            }
        }

        // 遍历位图, 输出被插入的数, 相当于做排序
        int base;
        int count;
        for (int i=0;i<bitmap.length;i++){
            count = 0;
            base = Integer.MIN_VALUE;
            while (base != 0){
                if ((bitmap[i] & base) != 0){
                    int r = (i<<5)+count;
                    System.out.println(r);
                }
                count++;
                base >>>= 1;
            }
        }

    }

    // 将input插入到bitmap中, 即修改对应bit位为1
    public static void put(int[] bitmap, int input){
        int index = input >> 5;
        int bit_index = input & 31;
        int base = Integer.MIN_VALUE;
        bitmap[index] |= (base >>> bit_index);
    }
}

 

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值