C语言代码实现,设散列表a[18],散列函数是hask(k)=k%17,用开放地址法解决冲突hi=(h0+di)%m。冲突时采用平方探测法,使用增量序列di=i* i。计算输入序列(值>=0)对应的散列地址并进行查找,如果有此元素,则输出散列地址,如果无此元素,则输出not found。并输出查找次数(输入个数不会超过15个)
时间: 2023-11-22 20:54:41 浏览: 165
下面是C语言代码实现:
```c
#include <stdio.h>
#define SIZE 18
int hash(int key) {
return key % 17;
}
int search(int a[], int key) {
int h, h0, d, i, count = 0;
h = hash(key);
h0 = h;
d = 1;
while (a[h] >= 0) {
if (a[h] == key) {
printf("Element found at index %d\n", h);
return count;
}
count++;
i++;
h = (h0 + i * i) % SIZE;
if (h == h0) {
break;
}
}
printf("Element not found\n");
return count;
}
int main() {
int a[SIZE] = {-1};
int n, i, count;
printf("Enter the number of elements: ");
scanf("%d", &n);
printf("Enter the elements: ");
for (i = 0; i < n; i++) {
int key;
scanf("%d", &key);
int h = hash(key);
int h0 = h;
int d = 1;
while (a[h] >= 0) {
i++;
h = (h0 + i * i) % SIZE;
if (h == h0) {
printf("Hash table is full\n");
return 0;
}
}
a[h] = key;
}
printf("Enter the element to search: ");
scanf("%d", &n);
count = search(a, n);
printf("Number of probes: %d\n", count);
return 0;
}
```
输入示例:
```
Enter the number of elements: 5
Enter the elements: 3 5 7 11 13
Enter the element to search: 7
```
输出示例:
```
Element found at index 7
Number of probes: 2
```
阅读全文