...
Here is an example implementation of a hash table using linear probing in C++:
Code Block | ||
---|---|---|
| ||
// main.cpp // LinearProbing // Created by Kevin Roark on 8/8/23. #include <iostream> #include <vector> using namespace std; class HashTable { private: int capacity; std::vector<int> keys; std::vector<int> values; int hash(int key) { return key % capacity; } public: HashTable(int capacity) : capacity(capacity), keys(capacity, -1), values(capacity, -1) {} // Initialize keys and values with -1, indicating empty slots void insert(int key, int value) { int index = hash(key); while (keys[index] != -1 && keys[index] != key) { index = (index + 1) % capacity; // Linear probing step } keys[index] = key; values[index] = value; } bool find(int key, int &value) { int index = hash(key); while (keys[index] != -1) { if (keys[index] == key) { value = values[index]; return true; } index = (index + 1) % capacity; // Linear probing step } return false; } void remove(int key) { int index = hash(key); while (keys[index] != -1) { if (keys[index] == key) { keys[index] = -1; values[index] = -1; return; } index = (index + 1) % capacity; // Linear probing step } } void print() { for (int i = 0; i < capacity; i++) { std::cout << "[" << i << "]: " << keys[i] << " -> " << values[i] << "\n"; } } }; int main() { HashTable hashTable(10); hashTable.insert(15, 150); hashTable.insert(25, 250); hashTable.insert(35, 350); hashTable.print(); int value; if (hashTable.find(25, value)) { std::cout << "Key 25 found with value: " << value << "\n"; } else { std::cout << "Key 25 not found\n"; } hashTable.remove(25); hashTable.print(); if (hashTable.find(25, value)) { std::cout << "Key 25 found with value: " << value << "\n"; } else { std::cout << "Key 25 not found\n"; } return 0; } |
Output:
...
Here, the linear probing is achieved by incrementing the index by 1 ((index + 1) % capacity
) each time a collision is detected until an empty slot or a slot with the same key is found.
...