java 位向量
public class BitVectory { private int count; private int[] a; private static final int BIT_LEN = 32; private static final int MASK = 0x1f; //16禁止表示 10进制31 private static final int SHIFT = 5; public BitVectory(int count) { this.count = count; init(count); } private void init(int count) { a = new int[(count - 1) / BIT_LEN + 1]; for (int i = 0; i < count; i++) { clear(i); } } private void clear(int i) { a[i >> SHIFT] &= ~ (1 << (i & MASK)); } // public void set(int i) { a[i >> SHIFT] |= (1 << (i & MASK)); } public List<Integer> getSortedArray() { List<Integer> list = new ArrayList<>(); StringBuilder s = new StringBuilder(); for (int i = 0; i < count; i++) { s.append(get(i)); if (get(i) == 1) { list.add(i); } } System.out.println(s.toString()); return list; } private int get(int i) { return Integer.bitCount(a[i >> SHIFT] & (1 << (i & MASK))); } public static void main(String[] args) { BitVectory bitVectory = new BitVectory(38); List<Integer> list = new ArrayList<>(38); for (int i = 0; i < 38; i++) { list.add((int) (Math.random() * 36)); } list.forEach(e -> { bitVectory.set(e); }); List<Integer> sortedArray = bitVectory.getSortedArray(); System.out.println(sortedArray.size() + "\t" + sortedArray); System.out.println(Integer.toBinaryString(bitVectory.a[0])); System.out.println(bitVectory.a.length); System.out.println(Arrays.toString(bitVectory.a)); } }
利用位向量对 0-N的数据进行排序 N / mask + 1个数组a来表示这些数