Hashing -Linear probing
Thu Oct 19 2023 14:26:43 GMT+0000 (Coordinated Universal Time)
Saved by
@Astik
#include <stdio.h>
#include <stdlib.h>
#define HASH_TABLE_SIZE 10
int hash(int key) {
return key % HASH_TABLE_SIZE;
}
int insert(int hashTable[], int key) {
int index = hash(key);
while (hashTable[index] != -1) {
index = (index + 1) % HASH_TABLE_SIZE;
}
hashTable[index] = key;
return index;
}
int search(int hashTable[], int key) {
int index = hash(key);
while (hashTable[index] != -1) {
if (hashTable[index] == key) {
return 1;
}
index = (index + 1) % HASH_TABLE_SIZE;
}
return 0;
}
void display(int hashTable[]) {
int i=0;
printf("Hash Table Contents:\n");
for (i = 0; i < HASH_TABLE_SIZE; i++) {
if (hashTable[i] != -1) {
printf("Index %d: %d\n", i, hashTable[i]);
} else {
printf("Index %d: NULL\n", i);
}
}
}
int main() {
int hashTable[HASH_TABLE_SIZE];
int choice,key;
int i;
for (i = 0; i < HASH_TABLE_SIZE; i++) {
hashTable[i] = -1;
}
while (choice!=4) {
printf("\nChoose an operation:\n");
printf("1. Display hash table\n");
printf("2. Insert a key\n");
printf("3. Search for a key\n");
printf("4. Exit\n");
scanf("%d", &choice);
switch (choice) {
case 1:
display(hashTable);
break;
case 2:
printf("Enter a key to insert: ");
scanf("%d", &key);
insert(hashTable, key);
printf("Key inserted into the hash table.\n");
break;
case 3:
printf("Enter a key to search: ");
scanf("%d", &key);
if (search(hashTable, key)) {
printf("%d is found in the hash table.\n", key);
} else {
printf("%d is not found in the hash table.\n", key);
}
break;
case 4:
exit(0);
default:
printf("Invalid choice. Please choose again.\n");
break;
}
}
return 0;
}
content_copyCOPY
Comments