数据结构:哈希表(除留取余法--线性探测法)

 #include <iostream>
#include <ctime>
using namespace std;


#define SUCCESS 1
#define UNSUCCESS 0
#define HASHSIZE 12
#define NULLKEY 0xffffffff/2
typedef struct  
{
	int *elem;
	int count;
}HashTable;
typedef int Status;

//初始化哈希表
Status InitHashTable( HashTable* pHashTable )
{
	if ( !pHashTable )
		return UNSUCCESS;
	pHashTable->count = 0;
	pHashTable->elem = new int[HASHSIZE];
	for ( int i = 0; i < HASHSIZE; ++i )
		pHashTable->elem[i] = NULLKEY;
	return SUCCESS;
}

//销毁哈希表
Status ClearHashTable( HashTable* pHashTable )
{
	if ( !pHashTable )
		delete[] pHashTable;
	return SUCCESS;
}

//哈希函数
int Hash( int key )
{
	return key % HASHSIZE; //除留取余法,根据前辈们的经验,若哈希表长为M,则取余因子P为小于
                                         //或等于表长(最好接近M)的最小质数或不包含小于20质因子的合数 
}

//插入关键字到哈希表
Status InsertHashTable( HashTable* pHashTable, int key )
{
	if ( !pHashTable )
		return UNSUCCESS;
	int addr = Hash( key );//求哈希地址
	while( pHashTable->elem[addr] != NULLKEY ) //不为空,则冲突了
		addr = ( addr + 1)% HASHSIZE;  //开放定址法:线性探测
	pHashTable->elem[addr] = key;
	pHashTable->count++;
	return SUCCESS;
}

//在哈希表中查找关键字记录
Status SearchHashTable( HashTable* pHashTable, int key, int *addr )
{
	if ( !pHashTable )
		return UNSUCCESS;
	*addr = Hash( key ); 
	while ( pHashTable->elem[*addr] != key )
	{
		*addr = (*addr + 1) % HASHSIZE; //开放定址法:线性探测
		if ( pHashTable->elem[*addr] == NULLKEY ||
			 *addr == Hash( key) )
		{
			return UNSUCCESS;
		}
	}
	return SUCCESS;
}


int main()
{
	HashTable _HashTable;
	InitHashTable( &_HashTable );
	int a[10] = { 3, 1, 6, 3, 8, 9, 10, 23, 12, 11};
	for ( int i = 0; i < 10; ++i )
	{
		InsertHashTable( &_HashTable, a[i] );
	}

	int key = 23;
	int addr;
	if ( !SearchHashTable( &_HashTable, key, &addr ) )
		return 0;
	cout << "元素索引为:" << addr << endl;
	return 0;
}

  • 7
    点赞
  • 36
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值