基于开发地址法的散列表的查找


#include <iostream>
using namespace std;
//利用线性探测法
typedef int keyType; 
typedef struct {
	keyType key;
}HashTable,*HashTree;
class Hash {
public:
	int curTable;//当前
	//定义哈希函数
	HashTree hashTable;
	int maxTable;//表长
	Hash(int length) {
		curTable = 0;
		maxTable = length;
		 hashTable=new HashTable[length];
		 for (int i = 0; i < length; i++)//初始化数值全为-1表示单元为空
			 hashTable[i].key = -1;
	}
	~Hash() {
		delete[]hashTable;
		hashTable = NULL;
	}
	//除留余数法
	int H(int key) {
		return key % 7;
	}//原来该落下的位置
	int hash(int key,int time) {
		return pow(time+1, 2);
	}//增量
	bool isFull() {
		return curTable == maxTable;
	}
	bool insert(int key) {
		if (isFull()) return false;
		int index = H(key);//原来该落的位置
		if (hashTable[index].key== -1) {//未被赋值
			hashTable[index].key = key;
			return true;
		}
		else {
			int newindex=0;
			int time = 0;
			while (true) {
				newindex = (index + hash(key,time++)) % maxTable;
				if (hashTable[newindex].key == -1) {
					hashTable[newindex].key = key;
					break;
				}
			}
		}
		curTable++;
	}
	void display()
	{
		for (int i = 0; i < maxTable; i++)
		{
			cout << i;
			if (hashTable[i].key != -1)
				cout << "---->" << hashTable[i].key;
			cout << endl;
		}
	}
};
//###重点:散列表的查找###//
int searchHash(Hash & h, keyType data) {
	//如果成功,则放回单元标号,否则返回-1
	int H0 = 0;
	H0=	h.H(data);
	if (h.hashTable[H0].key == -1) return -1;//没有存在
	else if (h.hashTable[H0].key == data)  return H0;//找到是在H0处
	else{
		for (int i = 1; i < h.maxTable; i++) {
			//按照线性探测法计算下一个散列地址Hi
			int Hi = (H0 + i) % h.maxTable;
			if (h.hashTable[Hi].key == -1) return -1;
			else if (h.hashTable[Hi].key == data) return Hi;
		}
		return -1;
	}
}

int main() {
	//针对课本课后习题
	/*
	对9,1,23,14,55,20,84,27,采用散列函数H(KEY)=KEY%7,表长度为10,开放地址法的二次探测法处理冲突
	*/
	int a[] = { 9,1,23,14,55,20,84,27 };
	int n = sizeof(a) / sizeof(a[0]);
	cout << "n=" << n << endl;
	Hash h(10);
	for (int i = 0; i < n; i++)
		h.insert(a[i]);
	h.display();
	keyType data;
	cout << "Please input the number you wanna locate" << endl;
	while (cin>>data) {
		if (searchHash(h, data) == -1) {
			cout << "不存在" << endl;
		}
		else
			cout <<data<< " locates at hashTable[" << searchHash(h, data) <<"]"<< endl;
		cout << "Please input the number you wanna locate" << endl;
	}
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

广大菜鸟

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值