Bitmap算法初学

经常听牛人谈论大数据处理时,都会提到bit-map算法,这个bit-map与我的专业中bitmap是有区别的,顾名思义前者就是数据位映射算法,后面是位图,一种图像存储方法。

其实所谓的Bit-map就是用一个bit位来标记某个元素对应的Value,而Key即是该元素。由于采用了Bit为单位来存储数据,因此在存储空间方面,可以大大节省。

如果说了这么多还没明白什么是Bit-map,那么我们来看一个具体的例子,假设我们要对0-7内的5个元素(4,7,2,5,3)排序(这里假设这些元素没有重复)。那么我们就可以采用Bit-map的方法来达到排序的目的。要表示8个数,我们就只需要8个Bit(1Bytes),首先我们开辟1Byte 的空间,将这些空间的所有Bit位都置为0(如下图:)

clip_image002

然后遍历这5个元素,首先第一个元素是4,那么就把4对应的位置为1(可以这样操作 p+(i/8)|(0x01<<(i%8)) 当然了这里的操作涉及到Big-ending和Little-ending的情况,这里默认为Big-ending),因为是从零开始的,所以要把第五位置为一(如下图),注:这里的方向与我们后面实际编程的存储是相反的,即实际上我们将0x01左移(i%8)位,比如i%8=0,就是左面第一位为1

clip_image004

然后再处理第二个元素7,将第八位置为1,,接着再处理第三个元素,一直到最后处理完所有的元素,将相应的位置为1,这时候的内存的Bit位的状态如下:

clip_image006

然后我们现在遍历一遍Bit区域,将该位是一的位的编号输出(2,3,4,5,7),这样就达到了排序的目的。

下面给出一个程序实例:

//定义每个Byte中有8个Bit位

#include <stdlib.h>

#include <memory.h>

#include <stdio.h>

#define ByteSize 8

void SetBit_num(char *p,int data,int blocksize){

    for(int i=0;i<blocksize;i++){                            //get block we wanted!

                       p++;  }

    *p=*p|(0x01<<(data%ByteSize));                  //storage of data into the p bit.

}

void BitmapSorted(int *arr){                              //allocate memeory for storage block

               int blocksize= MaxNum(arr);                                  //get max number in arry arr.

               char* buff= new char[blocksize];

               memset(buff,0,blocksize);

               for(int pNum=0;pNum<arrNum;pNum++){            //make the pNum number in arr to bit by bitmap algorithm

                         SetBit_num(buff,arr[pNum],blocksize);

                         }

               for(int i=0;i<blocksize;i++){

                     for(int j=0;j<ByteSize;j++){cout<<"Data sorted as follows: %d"<<i*ByteSize+j;}  //print the number in arr from small to big(right to left)

                         }

}

int main() {

       BitmapSorted();

       system("pause");

      return 0;

}

posted @ 2013-03-19 00:14  追风筝的小蜗牛  阅读(187)  评论(0)    收藏  举报