位图排序

来源:互联网 发布:寿光干部网络问政平台 编辑:程序博客网 时间:2024/05/12 10:56

利用位图对数据进行排序。

前提:待排数据不能有重复,且要能估计出待排数据值的上界(越精确效率越高)

时间复杂度:设待排数据值上界为M,待排数据量为N,则时间复杂度为O(2M+N)

c++实现代码:

#ifndef BITMAP_SORT_H#defineBITMAP_SORT_H//sort the array by bitmap, it demand all elements of src can't be repeated.const int WORD = 32;const int SHIFT = 5;  //left shift 5 bits equal to mutiply 32const int MASK = 0x1f;//31,M%N: if N%2=0, M%N = M&(N-1)const int MAX_VALUE = 10000000;  //The maximum value of all elements of src.int bitmap[MAX_VALUE/WORD+1];    //The array of bitmap.//set the bitvoid set(int i){bitmap[i>>SHIFT] |= (1<<(i&MASK));}//clear the bitvoid clear(int i){bitmap[i>>SHIFT] &= ~(1<<(i&MASK));}//return the result of the bitint test(int i){return (bitmap[i>>SHIFT] & (1<<(i&MASK)));}void bitmap_sort(int src[], int size){int i;for (i=0; i<MAX_VALUE; ++i){clear(i);}for (i=0; i<size; ++i){set(src[i]);}int j=0;for (i=0; i<MAX_VALUE; ++i){if (test(i)){src[j++] = i;}}}#endif


原创粉丝点击