zoukankan      html  css  js  c++  java
  • BitMap再体验之排序

    前言

    BitMap 初体验中我们了解了如何添加数据和判断数据是否存在,这次我们来说一下怎么排序。

    完整代码

    public class Demo {
        public static void main(String[] args) {
            BitMap bm = new BitMap(100);
            bm.add(1);
            bm.add(13);
            bm.add(57);
            bm.add(100);
    
            System.out.println("3:" + (bm.contains(3) ? "存在" : "不存在"));
            System.out.println("13:" + (bm.contains(13) ? "存在" : "不存在"));
    
            int[] result = sort(bm, 4);
    
            for (int i = 0; i < result.length; i++) {
                System.out.println(result[i]);
            }
    
        }
    
        public static int[] sort(BitMap bm, int length) {
            int[] arr = new int[length];
            byte[] bits = bm.getBits();
    
            int count = 0;
    
            for (int i = 0; i < bits.length; i++) {
                byte byt = bits[i];
                for (int j = 0; j < 8; j++) {
                    if ((byt & (1 << j)) != 0) {
                        arr[count++] = i * 8 + j;
                    }
                }
            }
    
            return arr;
        }
    }
    
    class BitMap {
        private byte[] bits;
        private int maxValue;
        private int capacity;
    
        public BitMap(int maxValue) {
            this.maxValue = maxValue;
            capacity = (maxValue >> 3) + 1;
            bits = new byte[capacity];
        }
    
        public void add(int num) {
            int index = num / 8;
            int position = num % 8;
            bits[index] |= (1 << position);
        }
    
        public boolean contains(int num) {
            int index = num / 8;
            int position = num % 8;
            return (bits[index] & (1 << position)) != 0;
        }
    
        public byte[] getBits() {
            return bits;
        }
    }
    

    排序

    我们主要看sort方法,其实我们在进行添加数据的时候已经对数据进行了排序,在排序这个方法中我们需要做的仅仅是将排好序的数据读出即可:

    1. 遍历byte数组中的所有byte;
    2. 遍历当前byte的所有bit,需要注意的是这里对每个bit位的判断都是用的"位与"运算;
    3. 算出当前bit位对应的值,index * 8 + position, 这个公式是根据前面 index = N / 8, position = N % 8 可以推出;
  • 相关阅读:
    spring + velocity实现分页程序
    Velocity分页模板
    .Net之NVelocity的三种用法
    .Net下模板引擎NVelocity的封装类――VelocityHelper
    NVelocity系列:NVelocity的语法及指令
    Velocity用户手册
    NVelocity的增强功能
    NVelocity配置详解
    报Error creating bean with name 'dataSource' defined in class path resource 报错解决办法
    如何向老外索要代码【转】
  • 原文地址:https://www.cnblogs.com/lwmp/p/13634130.html
Copyright © 2011-2022 走看看