ahmadalibin
ahmadalibin

Reputation: 141

Insert elements of array into hash table

I want to write some code that will insert elements from an array into the hash table below. I'm using the array "a" as a test array to see if I can insert elements into the hash table. However when I run the code, only the first element gets inserted into the hash table and the rest of the keys remain empty.

#include<iostream>
#include<cstdlib>
#include<string>
#include<cstdio>
using namespace std;

struct table
{
    int key;
    int val;
    table()
    {
        
    }
    table(int k, int v)
    {
        key = k;
        val = v;
    }
};
 
void INSERT(table T[], table x)
{
    T[x.key] = x;
}
 
void DELETE(table T[], table x)
{
    T[x.key] = table(0, 0);
}
 
table SEARCH(table T[], int k)
{
    return T[k];
}
 
int main()
{
    int a[] = {15, 11, 27, 8, 12}; 
    int n = sizeof(a)/sizeof(a[0]);
    int i, key, val;
    table T[n];
    table x;
    for(i = 0; i < n; i++) {
        T[i] = table(0, 0);
        key=i+1;
        val=a[i];
        INSERT(T, table(key, val));
        
        x = SEARCH(T, 1);
        if (x.key == 0)
        {
            cout<<"No element inserted at the key "<< key <<endl;
        } else {
            cout<<"Element at key "<< key <<" is-> "<< x.val <<endl;
        }
    }
    return 0;
}

Upvotes: 0

Views: 753

Answers (2)

darklaser28
darklaser28

Reputation: 11

Well here u have passed in the call-site INSERT(), 1 as k so the incrementation that you have set (key+=1) wont be used and the value at key 1 will never be searched.. During the iteration it will keep on searching value at k=1 that doesn't exist

Upvotes: 1

The Philomath
The Philomath

Reputation: 992

Problem is with this line

x = SEARCH(T, 1);

Replace 1 by key

x = SEARCH(T, key);

Upvotes: 1

Related Questions