hashing code
✅ 1️⃣ Open Hashing (Separate Chaining)
👉 list use ki
👉 insert + delete + display
👉 sab functions, call from main()
#include <iostream>
#include <list>
using namespace std;
#define SIZE 5
// INSERT
void insertOpen(list<int> table[], int key) {
int index = key % SIZE;
table[index].push_back(key);
}
// DELETE
void deleteOpen(list<int> table[], int key) {
int index = key % SIZE;
table[index].remove(key);
}
// DISPLAY
void displayOpen(list<int> table[]) {
for (int i = 0; i < SIZE; i++) {
cout << i << " : ";
for (int x : table[i])
cout << x << " -> ";
cout << "NULL\n";
}
}
int main() {
list<int> table[SIZE];
insertOpen(table, 10);
insertOpen(table, 15);
insertOpen(table, 20);
deleteOpen(table, 15);
displayOpen(table);
}
✅ 2️⃣ Linear Probing (Closed Hashing)
👉 array only
👉 tombstone delete
👉 sab functions
#include <iostream>
using namespace std;
#define SIZE 7
#define EMPTY -1
#define DELETED -2
void init(int table[]) {
for (int i = 0; i < SIZE; i++)
table[i] = EMPTY;
}
// INSERT
void insertLinear(int table[], int key) {
int index = key % SIZE;
while (table[index] != EMPTY && table[index] != DELETED)
index = (index + 1) % SIZE;
table[index] = key;
}
// DELETE
void deleteLinear(int table[], int key) {
int index = key % SIZE;
while (table[index] != EMPTY) {
if (table[index] == key) {
table[index] = DELETED;
return;
}
index = (index + 1) % SIZE;
}
}
// DISPLAY
void display(int table[]) {
for (int i = 0; i < SIZE; i++)
cout << i << " : " << table[i] << endl;
}
int main() {
int table[SIZE];
init(table);
insertLinear(table, 10);
insertLinear(table, 17);
insertLinear(table, 24);
deleteLinear(table, 17);
display(table);
}
✅ 3️⃣ Quadratic Probing (Closed Hashing)
👉 + i² jump
👉 functions only
#include <iostream>
using namespace std;
#define SIZE 7
#define EMPTY -1
#define DELETED -2
void init(int table[]) {
for (int i = 0; i < SIZE; i++)
table[i] = EMPTY;
}
// INSERT
void insertQuadratic(int table[], int key) {
int index = key % SIZE;
for (int i = 0; i < SIZE; i++) {
int newIndex = (index + i*i) % SIZE;
if (table[newIndex] == EMPTY || table[newIndex] == DELETED) {
table[newIndex] = key;
return;
}
}
}
// DELETE
void deleteQuadratic(int table[], int key) {
int index = key % SIZE;
for (int i = 0; i < SIZE; i++) {
int newIndex = (index + i*i) % SIZE;
if (table[newIndex] == EMPTY)
return;
if (table[newIndex] == key) {
table[newIndex] = DELETED;
return;
}
}
}
// DISPLAY
void display(int table[]) {
for (int i = 0; i < SIZE; i++)
cout << i << " : " << table[i] << endl;
}
int main() {
int table[SIZE];
init(table);
insertQuadratic(table, 10);
insertQuadratic(table, 17);
insertQuadratic(table, 24);
deleteQuadratic(table, 17);
display(table);
}