Linear Probing - Delete Function Not Working Properly

92 views Asked by At

Here's a snippet of a Linear Probing program that I'm working on. I'm focusing on the insertElement and deleteElement functions:

class HashMapTable
{
    // initializing the size of the hash table
    int table_size;

    // a pointer* vector that points to an array on the hash table containing the keys
    vector<int>* table;

public:
    // creating a parameterized constructor of the above class containing all the methods
    HashMapTable(int key);

    // hash function formula to compute the index using table_size and key
    int hashFunction(int key) {
        return (key % table_size);
    }

    // inserting a key in the hash table
    void insertElement(int key);

    // deleting a key in the hash table
    void deleteElement(int key);
void HashMapTable::insertElement(int key)
{
    int index = hashFunction(key); // index of array equating to the key%table_size

    if (table[index].empty()) {
        table[index].push_back(key);
    }
    else {
        do {
            index = (index + 1) % table_size;   // temp_key % table_size
        } while (!table[index].empty());
        table[index].push_back(key);
        
        cout << table[index].at(0) << " has been shifted by " << index << " iteration(s)" << endl;
    }

void HashMapTable::deleteElement(int key)
{
    int index = hashFunction(key);
    
    auto i = find(table[index].begin(), table[index].end(), key);
    if (i != table[index].end())
        table[index].erase(i);  

    cout << key << "'s true index is found at " << index << ". ";
    cout << key << " modulo " << table_size << " is " << key % table_size << "\n\n";
}
int main()
{
    // array of all the keys to be inserted in the hash table
    int arr[] = { 20, 34, 56, 54, 76, 87 };
    int n = sizeof(arr) / sizeof(arr[0]);

    // table_size of hash table as 6
    HashMapTable ht(6);
    for (int i = 0; i < n; i++)
        ht.insertElement(arr[i]);

    // deleting a key from the hash table
    ht.deleteElement(87);

    // displaying the final data of hash table
    ht.displayHashTable();

    return 0;
}

Here is the output:

56 has been shifted by 3 iteration(s)
76 has been shifted by 5 iteration(s)
87 has been shifted by 1 iteration(s)
87's true index is found at 3. 87 modulo 6 is 3

0 ==> 54
1 ==> 87
2 ==> 20
3 ==> 56
4 ==> 34
5 ==> 76

I'm attempting to delete element 87 from the vector, but the deleteElement function seems to reading the initial modulo of each element and attempting to delete them from their initial positions, even though the insertElement already shifted them to an empty slot. I'm very confused as to why this is happening.

0

There are 0 answers