利用位图对数据进行排序。
前提:待排数据不能有重复,且要能估计出待排数据值的上界(越精确效率越高)
时间复杂度:设待排数据值上界为M,待排数据量为N,则时间复杂度为O(2M+N)
c++实现代码:
#ifndef BITMAP_SORT_H
#define BITMAP_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 32
const 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 bit
void set(int i)
{
bitmap[i>>SHIFT] |= (1<<(i&MASK));
}
//clear the bit
void clear(int i)
{
bitmap[i>>SHIFT] &= ~(1<<(i&MASK));
}
//return the result of the bit
int 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