Skip to main content

Create a hash table and handle the collisions using linear probing with replacement.

CODE:


 #include <iostream>

#include <vector>

#include <string>


using namespace std;


// Define a class for the hash table

class HashTable {

private:

    vector<pair<string, int>> table;

    int capacity;

    int size;


    // Hash function

    int hash(const string& key) {

        int hash = 0;

        for (char c : key) {

            hash += c;

        }

        return hash % capacity;

    }


    // Helper function to find the next available slot using linear probing

    int findNextAvailable(int index) {

        int i = index + 1;

        while (table[i].first != "") {

            i = (i + 1) % capacity;

        }

        return i;

    }


public:

    // Constructor

    HashTable(int capacity) : capacity(capacity), size(0) {

        table.resize(capacity);

    }


    // Function to insert a key-value pair into the hash table

    void insert(const string& key, int value) {

        int index = hash(key);

        if (table[index].first == "") {

            table[index] = make_pair(key, value);

            size++;

        } else {

            // Handle collision using linear probing with replacement

            int nextAvailable = findNextAvailable(index);

            table[nextAvailable] = make_pair(key, value);

            size++;

        }

    }


    // Function to search for a key in the hash table

    int search(const string& key) {

        int index = hash(key);

        int originalIndex = index;

        while (table[index].first != key && table[index].first != "") {

            index = (index + 1) % capacity;

            if (index == originalIndex) {

                return -1; // Key not found

            }

        }

        if (table[index].first == key) {

            return table[index].second;

        } else {

            return -1; // Key not found

        }

    }

};


int main() {

    // Create a hash table with capacity 10

    HashTable ht(10);


    // Insert some key-value pairs

    ht.insert("John", 25);

    ht.insert("Emma", 30);

    ht.insert("Bob", 35);


    // Search for keys

    cout << "Age of John: " << ht.search("John") << endl;

    cout << "Age of Emma: " << ht.search("Emma") << endl;

    cout << "Age of Bob: " << ht.search("Bob") << endl;

    cout << "Age of Alice: " << ht.search("Alice") << endl; // Key not found


    return 0;

}