位图排序

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

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

时间复杂度:设待排数据值上界为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


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值