package lpc.Algorithm;
public class My_BitSet {
private int[] mBits;
public int[] getmBits() {
return mBits;
}
private int mSize;
/**
* 构造函数
* @param size 初始化mBits 的长度
*/
public My_BitSet(int size) {
// TODO Auto-generated constructor stub
mSize = size;
initBits();
}
//初始化整形数组
private void initBits() {
// TODO Auto-generated method stub
int count = (int) Math.ceil(mSize/32f)+1;
mBits =new int[count];
}
/**
* 将制定bit位置设置为1
* @param pos
*/
public void set(int pos){
//得到此pos在myits中的位置
//int index = (int)Math.floor(pos/32f);
int index = pos >> 5;
//把当前整数的地n位设置为1
//mBits[index] = mBits[index] | (1<<(pos%32));
mBits[index] = mBits[index] | (1<<(pos & 0x1F));
}
/**
* 获取指定位置是否存在
* @param pos
* @return
*/
public boolean get(int pos){
//int index = (int)Math.floor(pos/32f);
int index = pos >> 5;
//return mBits[index] == (mBits[index] | 1 <<(pos%32));
return mBits[index] == (mBits[index] | 1 <<(pos & 0x1F));
}
public void reset(int pos){
int index = (int)Math.floor(pos/32f);
//把当前整数的第n位设置为0
mBits[index] = mBits[index] & ~(1<<(pos%32));
}
/**
* 清空,全部置0
* @param args
*/
public void clear(){
int len = mBits.length;
for (int index = 0; index < len; index++) {
mBits[index] = 0 ;
}
}
public static void main(String[] args) {
//int[] a=new int[]{509,9,8,300,6,5,4,3,2,1,0};
int N=100000000;
int[] a=new int[N];
for (int i = 0; i < a.length; i++) {
a[i]=N-i-1;
}
int max=a[0];
for (int i : a) {
if (i>max) {
max=i;
}
}
long start = System.currentTimeMillis();
My_BitSet bitSet = new My_BitSet(max);
//设置值
for (int i : a) {
bitSet.set(i);
}
for (int i=0 ; i<=max; i++) {
if(bitSet.get(i)){};//防止刷屏只判断,什么也不做
}
long end = System.currentTimeMillis();
System.out.format("usetime: %d ms",(end-start));
/*
System.out.println("----------打印原数组----------");
for (int i : a) {
if(bitSet.get(i)){
System.out.println(i);
}
}
System.out.println("---------打印排序后数组-------------");
for (int i=0 ; i<=max; i++) {
if(bitSet.get(i)){
System.out.println(i);
}
}
*/
}
}