散列技术(哈希表)-线性探测法

散列技术(Hash表)-线性探测法(哈工大版)

虽然线性探测法查找时间上不如链地址法优,但对于少量数据用线性探测法也很方便。
二话不说,上代码,注释详细。

C++代码

/***** 散列技术 *****/
/* 测试样例(输入10个自然数):
3 4 0 22 33 44 23 24 25 26
输入查找的值:
26
*/
#include
using namespace std;
#define max 11
#define B 11
#define h(key) key % B   //hash函数

/***** 开放地址法--线性探测法 *****/

struct record {
	int key;
};

typedef record Hash[max];   //Hash表

int Search(int R, Hash F) {   //在F中搜索R值
	int locate, first, rehash;
	locate = first = h(R), rehash = 0;
	while (rehash < max && F[locate].key != -1) {   //-1 = empty
		if (F[locate].key == R)  return locate;
		else  rehash++;
		locate = (first + rehash) % B;
	}
	return -1;
}

void Insert(int R, Hash F) {   //在F中插入R值
	int locate, first, rehash;
	locate = first = h(R), rehash = 0;
	while (rehash < max && F[locate].key != R) {
		locate = (first + rehash) % B;
		if (F[locate].key == -1)  F[locate].key = R;
		else  rehash++;
	}
	if (rehash >= max)  cout << "Hash table is full !" << endl;
}

void Delete(int key, Hash F) {   //在F中删除key值
	int locate = Search(key, F);
	if (locate != -1)
		F[locate].key = -1;   //-1 = empty = deleted
}

void InitHash(Hash F) {   //初始化F
	for (int i = 0; i < max; i++)
		F[i].key = -1;   //-1 = empty
}
void PrintHash(Hash F) {   //遍历F
	for (int i = 0; i < max; i++)
		cout << "Hash" << i << " = " << F[i].key << endl;
}
int main() {
	Hash f;
	InitHash(f);
	int temp;
	for (int i = 0; i < 10; i++) {
		cin >> temp;
		Insert(temp, f);
	}
	cin >> temp;
	cout <<"查找函数返回的值:"<< Search(temp, f) << endl;
	PrintHash(f);
	Delete(temp, f);   //删除查找到的值
	PrintHash(f);   //遍历以验证
	return 0;
}

你可能感兴趣的:(c/c++数据结构,散列表,数据结构,算法,哈希算法,c++)