哈希查找

// 将数组array通过除数取余法分散到hash数组中
void BuildHash(int *hash, int *array, int n)
{
	bool flag[HASH_LENGTH] = {false};
	int index;

	for(int i = 0; i < n; i++)
	{
		index = array[i] % HASH_LENGTH;
		if(!flag[index])
		{
			hash[index] = array[i];
			flag[index] = true;
		}
		else
		{
			while(flag[++index%HASH_LENGTH]);
			hash[index] = array[i];
			flag[index] = true;
		}
	}

}

// 从hash散列中寻找key
// hash地址冲突采用开放地址探测法解决
int SearchHash(int *hash, int key)
{
	int index = key % HASH_LENGTH;

	if(key == hash[index])
	{
		return index;
	}
	else
	{
		int temp = index;

		while((key != hash[++index%HASH_LENGTH]) && (index%HASH_LENGTH != temp));
		if(key == hash[index])
		{
			return index;
		}
	}
	return -1;
}

int BinarySearch(int *array, int n, int key)
{
	int hash[HASH_LENGTH];
	init(hash, HASH_LENGTH);
	BuildHash(hash, array, n);
	return SearchHash(hash, key);
}
posted @ 2013-12-03 16:49  a ray of sunshine  阅读(147)  评论(0编辑  收藏  举报