Design and develop a program in C that uses Hash Function H:K->L as H(K)=K mod m(reminder method) and implement hashing technique to map a given key K to the address space L. Resolve the collision (if any) using linear probing.
#include <stdio.h>
#include <stdlib.h>
#define MAX 100
#define NULL_KEY -1
int m; // size of hash table
int ht[MAX]; // hash table
int hash(int key) {
return key % m;
}
void insert(int key) {
int index = hash(key);
while (ht[index] != NULL_KEY) {
index = (index + 1) % m;
}
ht[index] = key;
}
int search(int key) {
int index = hash(key);
int counter = 0;
while (counter++ < m && ht[index] != NULL_KEY && ht[index] != key) {
index = (index + 1) % m;
}
return (ht[index] == key) ? index : -1;
}
void display() {
int i;
printf("\nHash Table:\n");
for (i = 0; i < m; i++) {
printf("%d ", ht[i]);
}
printf("\n");
}
int main() {
int n, i, key, index;
printf("Enter the size of hash table: ");
scanf("%d", &m);
for (i = 0; i < m; i++) {
ht[i] = NULL_KEY;
}
printf("Enter the number of elements: ");
scanf("%d", &n);
printf("Enter the elements: ");
for (i = 0; i < n; i++) {
scanf("%d", &key);
insert(key);
}
display();
printf("Enter the element to be searched: ");
scanf("%d", &key);
index = search(key);
if (index == -1) {
printf("Element not found\n");
} else {
printf("Element found at index %d\n", index);
}
return 0;
}