利用位圖對數據進行排序。
前提:待排數據不能有重複,且要能估計出待排數據值的上界(越精確效率越高)
時間複雜度:設待排數據值上界爲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