C语言散列查找(线性探测法)代码
时间: 2023-12-09 14:03:54 浏览: 141
Sure, here's an example of C language code implementing hashing with linear probing:
```c
#include <stdio.h>
#include <stdlib.h>
#define SIZE 10
int hash(int key)
{
return key % SIZE; // simple hash function using modulo operator
}
int probe(int hash_val)
{
return (hash_val + 1) % SIZE; // linear probing function
}
void insert(int *arr, int key)
{
int idx = hash(key); // calculate hash value
// linear probing to find next available index
while (arr[idx] != -1) {
idx = probe(idx);
}
arr[idx] = key; // insert key
}
int search(int *arr, int key)
{
int idx = hash(key); // calculate hash value
// linear probing to find key
while (arr[idx] != -1) {
if (arr[idx] == key) {
return idx;
}
idx = probe(idx);
}
return -1; // key not found
}
int main()
{
int arr[SIZE];
for (int i = 0; i < SIZE; i++) {
arr[i] = -1; // initialize array with -1
}
// insert keys into array
insert(arr, 5);
insert(arr, 12);
insert(arr, 23);
insert(arr, 1);
insert(arr, 7);
// search for keys in array
printf("Index of 12: %d\n", search(arr, 12));
printf("Index of 23: %d\n", search(arr, 23));
printf("Index of 9: %d\n", search(arr, 9));
return 0;
}
```
I hope this helps! Do you have any other questions?
阅读全文