B : DS哈希查找—线性探测再散列

Description

定义哈希函数为H(key) = key%11,输入表长(大于、等于11)。输入关键字集合,用线性探测再散列构建哈希表,并查找给定关键字。

–程序要求–

若使用C++只能include一个头文件iostream;若使用C语言只能include一个头文件stdio

程序中若include多过一个头文件,不看代码,作0分处理

不允许使用第三方对象或函数实现本题的要求

Input

测试次数t

每组测试数据为:

哈希表长m、关键字个数n

n个关键字

查找次数k

k个待查关键字

Output

对每组测试数据,输出以下信息:

构造的哈希表信息,数组中没有关键字的位置输出NULL

对k个待查关键字,分别输出:0或1(0—不成功,1—成功)、比较次数、查找成功的位置(从1开始)

Sample

Input
1
12 10
22 19 21 8 9 30 33 4 15 14
4
22
56
30
17
Output
22 30 33 14 4 15 NULL NULL 19 8 21 9
1 1 1
0 6
1 6 2
0 1

Hint

注意查找的终止条件,comparison应该小于hashTable的len,避免死循环。

Code

#include<iostream>
using namespace std;

void init(int*& hashTable, int m) {
	for (int i = 0; i < m; i++) {
		hashTable[i] = -1;
	}
}

// 线性探测再散列插入
void insert(int* hashTable, int m, int key) {
	int index = key % 11;
	while (hashTable[index] != -1) {
		index = (index + 1) % m;
	}
	hashTable[index] = key;
}

// 线性探测再散列查找
void search(int*& hashTable, int m, int key, int& comparisons) {
	int index = key % 11;
	comparisons = 1;
	while (hashTable[index] != -1 && hashTable[index] != key) {
		if (comparisons >= m)
			break;
		index = (index + 1) % m;
		comparisons++;
	}
	if (hashTable[index] == key) {
		cout << "1 " << comparisons << " " << index + 1;
	}
	else
		cout << "0 " << comparisons ;
	cout << endl;
}

void print(int* hashTable, int m) {
	for (int i = 0; i < m; i++) {
		if (hashTable[i] != -1)
			cout << hashTable[i] << " ";
		else cout << "NULL ";
	}
	cout << endl;
}

int main() {
	int t, m, n, k, key;
	cin >> t;
	while (t--) {
		cin >> m >> n;
		int* hashTable = new int[m];
		init(hashTable, m);

		/* ...n个关键字... */
		for (int i = 0; i < n; i++) {
			cin >> key;
			insert(hashTable, m, key);
		}
		print(hashTable, m);

		cin >> k;
		while (k--) {
			cin >> key;
			/* 查找key */
			int comparsions;
			search(hashTable, m, key, comparsions);
		}
		delete[]hashTable;
	}

	return 0;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值