hashing
hashing
h>
#include <stdlib.h>
#define TABLE_SIZE 10
typedef struct Node {
int key;
struct Node* next;
} Node;
int hashFunction(int key) {
return key % TABLE_SIZE;
}
Node* chainTable[TABLE_SIZE] = {NULL};
int linearTable[TABLE_SIZE];
int quadraticTable[TABLE_SIZE];
void initOpenAddressing() {
for (int i = 0; i < TABLE_SIZE; i++) {
linearTable[i] = -1;
quadraticTable[i] = -1;
}
}
void insertChaining(int key) {
int index = hashFunction(key);
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->key = key;
newNode->next = chainTable[index];
chainTable[index] = newNode;
}
int searchChaining(int key) {
int index = hashFunction(key);
Node* current = chainTable[index];
while (current) {
if (current->key == key)
return 1;
current = current->next;
}
return 0;
}
void insertLinearProbing(int key) {
int index = hashFunction(key);
int originalIndex = index;
while (linearTable[index] != -1) {
index = (index + 1) % TABLE_SIZE;
if (index == originalIndex) {
printf("Hash table is full (linear probing).\n");
return;
}
}
linearTable[index] = key;
}
void insertQuadraticProbing(int key) {
int index = hashFunction(key);
int i = 1, originalIndex = index;
while (quadraticTable[index] != -1) {
index = (originalIndex + i * i) % TABLE_SIZE;
if (index == originalIndex) {
printf("Hash table is full (quadratic probing).\n");
return;
}
i++;
}
quadraticTable[index] = key;
}
void displayHashTable() {
printf("\nChaining:\n");
for (int i = 0; i < TABLE_SIZE; i++) {
printf("[%d]:", i);
Node* current = chainTable[i];
while (current) {
printf(" -> %d", current->key);
current = current->next;
}
printf("\n");
}
printf("\nLinear Probing:\n");
for (int i = 0; i < TABLE_SIZE; i++) {
if (linearTable[i] == -1)
printf("[%d]: -\n", i);
else
printf("[%d]: %d\n", i, linearTable[i]);
}
printf("\nQuadratic Probing:\n");
for (int i = 0; i < TABLE_SIZE; i++) {
if (quadraticTable[i] == -1)
printf("[%d]: -\n", i);
else
printf("[%d]: %d\n", i, quadraticTable[i]);
}
}
int main() {
initOpenAddressing();
int n, key, searchKey;
printf("Enter the number of keys to insert: ");
scanf("%d", &n);
printf("Enter %d keys:\n", n);
for (int i = 0; i < n; i++) {
scanf("%d", &key);
insertChaining(key);
insertLinearProbing(key);
insertQuadraticProbing(key);
}
displayHashTable();
printf("\nEnter a key to search: ");
scanf("%d", &searchKey);
printf("Searching for key %d in chaining: %s\n",
searchKey,
searchChaining(searchKey) ? "Found" : "Not Found");
return 0;
}