Content Beyond Document - CPDS
Content Beyond Document - CPDS
ACD-
COLLEGE OF ENGINEERING & TECHNOLOGY CF-CBL
Elupatti, Thanjavur – 613 403 Issue No. 01
CONTENT BEYOND SYLLABUS Rev. No. 00
Program
#include <stdio.h>
#include <stdlib.h>
#define TABLE_SIZE 10
#define EMPTY -1
int hashTable[TABLE_SIZE];
// Hash function
int hashFunction(int key) {
return key % TABLE_SIZE;
}
// Insert a key into the hash table
void insert(int key) {
int index = hashFunction(key);
while (hashTable[index] != EMPTY) {
index = (index + 1) % TABLE_SIZE; // Linear probing
}
hashTable[index] = key;
}
// Search for a key in the hash table
int search(int key) {
int index = hashFunction(key);
int startIndex = index;
while (hashTable[index] != EMPTY) {
if (hashTable[index] == key) return 1; // Found
index = (index + 1) % TABLE_SIZE;
if (index == startIndex) break; // Full circle
}
return 0; // Not found
}
// Display the hash table
void display() {
for (int i = 0; i < TABLE_SIZE; i++) {
if (hashTable[i] != EMPTY) {
printf("Bucket %d: %d\n", i, hashTable[i]);
} else {
printf("Bucket %d: EMPTY\n", i);
}
}
}
int main() {
// Initialize hash table
for (int i = 0; i < TABLE_SIZE; i++) {
hashTable[i] = EMPTY;
}
insert(10);
insert(20);
insert(15);
insert(25);
display();
printf("Search 15: %s\n", search(15) ? "Found" : "Not Found");
printf("Search 30: %s\n", search(30) ? "Found" : "Not Found");
return 0;
}
Output
Search Operations
1. Search 15:
o hashFunction(15) = 15 % 10 = 5.
o Bucket 5 contains 15, so the key is found.
o Output: Search 15: Found.
2. Search 30:
o hashFunction(30) = 30 % 10 = 0.
o Bucket 0 contains 10, which is not 30, so linear probing is used.
o Bucket 1 contains 20, which is not 30.
o The search continues until all buckets are checked or an EMPTY bucket is
reached.
o Bucket 2 is EMPTY, so the key is not found.
o Output: Search 30: Not Found.
Final Output
Bucket 0: 10
Bucket 1: 20
Bucket 2: EMPTY
Bucket 3: EMPTY
Bucket 4: EMPTY
Bucket 5: 15
Bucket 6: 25
Bucket 7: EMPTY
Bucket 8: EMPTY
Bucket 9: EMPTY