题目描述
采用除留余数法(H(key)=key %n)建立长度为n的哈希表,处理冲突用开放定址法的线性探测。
输入
第一行为哈希表的长度n; 第二行为关键字的个数; 第三行为关键字集合; 第三行为要查找的数据。
输出
如果查找成功,输出关键字所哈希表中的地址和比较次数;如果查找不成功,输出-1。
#include<bits/stdc++.h>
using namespace std;
int main() {
int hash[50] = {0}, a[50], m, n, data, cnt = 0;
cin >> n >> m;
for (int i = 0; i < m; ++i) {
cin >> a[i];
int temp = a[i] % n;
while(hash[temp] != 0 && temp < 50) temp ++;
hash[temp] = a[i];
}
cin >> data;
int temp = data % n;
while(hash[temp] != 0 && hash[temp] != data && temp < 50){
temp ++;
cnt ++;
}
if (hash[temp] == data) cout << temp << "," << cnt + 1;
else cout << -1;
return 0;
}