1. 位图结构的实现
public class BitMap { private byte [ ] bytes; private int capacity; private static final int DEFAULT_CAPACITY = 32 ; public BitMap ( ) { this ( DEFAULT_CAPACITY ) ; } public BitMap ( int capacity) { this . capacity = capacity; this . bytes = new byte [ ( capacity >> 3 ) + 1 ] ; } public void add ( int num) { bytes[ index ( num) ] |= ( iterateByte ( num) ) ; } public void delete ( int num) { bytes[ index ( num) ] &= ( ~ iterateByte ( num) ) ; } public boolean contains ( int num) { return ( bytes[ index ( num) ] & iterateByte ( num) ) != 0 ; } private int index ( int num) { return num >> 3 ; } private int iterateByte ( int num) { return 1 << ( num & 0x07 ) ; } public byte [ ] getBytes ( ) { return bytes; } public int getCapacity ( ) { return capacity; }
}
2. 利用位图排序
public void sortByBitMap ( ) { int [ ] arr = { 4 , 9 , 2 , 17 , 3 , 10 } ; BitMap bitMap = new BitMap ( ) ; for ( int i : arr) { bitMap. add ( i) ; } List < Integer > result = new ArrayList < > ( ) ; byte [ ] bytes = bitMap. getBytes ( ) ; for ( int i = 0 ; i < bytes. length; i++ ) { for ( int j = 0 ; j < 8 ; j++ ) { if ( ( bytes[ i] & ( 1 << j) ) == ( 1 << j) ) { result. add ( ( i << 3 ) + j) ; } } } System . out. println ( result) ;
}