#include <stdio.h>
#define TABLE_SIZE 7
int hash(int key) {
return key % TABLE_SIZE;
}
void insert(int table[], int key) {
int index = hash(key);
int start_index = index;
while (table[index] != -1) {
index = (index + 1) % TABLE_SIZE; // move to next slot
if (index == start_index) {
printf("Hash table is full, cannot insert %d\n", key);
return;
}
}
table[index] = key;
}
void print_table(int table[]) {
printf("Hash Table:\n");
for (int i = 0; i < TABLE_SIZE; i++) {
if (table[i] == -1) {
printf("[%d]: empty\n", i);
} else {
printf("[%d]: %d\n", i, table[i]);
}
}
}
int main() {
int table[TABLE_SIZE];
for (int i = 0; i < TABLE_SIZE; i++) {
table[i] = -1; // initialize all slots as empty
}
insert(table, 10);
insert(table, 20);
insert(table, 30);
insert(table, 17);
print_table(table);
return 0;
}compute initial slot using hash function
while (table[index] != -1) {
check if slot is occupied to handle collision
index = (index + 1) % TABLE_SIZE; // move to next slot
move to next slot in linear probing
if (index == start_index) {
detect full table to stop infinite loop
insert key into found empty slot
Hash Table:
[0]: empty
[1]: empty
[2]: 30
[3]: 10
[4]: 17
[5]: empty
[6]: 20