Double Hashing
Double Hashing
#include <vector>
class HashTable {
private:
int tableSize;
int count;
std::vector<int> table;
public:
HashTable(int size) {
tableSize = size;
count = 0;
table.resize(tableSize, -1);
// Choose a second hash function that returns a value relatively prime to tableSize
}
void insertDoubleHashing(int key) {
int step = hash2(key); // Compute step size using second hash function
int i = 0;
while (table[(index + i * step) % tableSize] != -1) { // Continue probing until an empty slot is found
return;
int step = hash2(key); // Compute step size using second hash function
int i = 0;
while (table[(index + i * step) % tableSize] != key) { // Continue probing until key is found or an
empty slot is reached
if (table[(index + i * step) % tableSize] == -1) { // If empty slot is reached, key is not present
std::cout << "Key " << key << " not found." << std::endl;
return;
}
table[(index + i * step) % tableSize] = -1; // Mark the slot as empty
std::cout << "Key " << key << " deleted." << std::endl;
int step = hash2(key); // Compute step size using second hash function
int i = 0;
while (table[(index + i * step) % tableSize] != key) { // Continue probing until key is found or an
empty slot is reached
if (table[(index + i * step) % tableSize] == -1) // If empty slot is reached, key is not present
return false;
void printTable() {
std::cout << "Index " << i << ": " << table[i] << std::endl;
};
int main() {
HashTable ht(10);
ht.insertDoubleHashing(4322);
ht.insertDoubleHashing(1334);
ht.insertDoubleHashing(1471);
ht.insertDoubleHashing(9679);
ht.insertDoubleHashing(1989);
ht.insertDoubleHashing(6171);
ht.insertDoubleHashing(6173);
ht.insertDoubleHashing(4199);
ht.printTable();
std::cout << "Searching for key 1334: " << (ht.searchDoubleHashing(1334) ? "Found" : "Not Found") <<
std::endl;
std::cout << "Searching for key 1234: " << (ht.searchDoubleHashing(1234) ? "Found" : "Not Found") <<
std::endl;
ht.deleteDoubleHashing(1334);
ht.deleteDoubleHashing(1234);
ht.printTable();
return 0;