Sunday, October 27, 2013

Hash Table in C++

#include <iostream>
#include<string.h>
#include<stdio.h>
#define hash(x) x%10
using namespace std;
struct emp
{
    int empid;
    char name[30];
    float salary;
};
class ht
{
    emp ht[10];
    int link[10];
    public:
    void insert();
    void enter(emp x);
    void display();
    void del(int a);
    void search(int i);
};
void ht :: insert()
{
    int x;
    for(int p=0;p<10;p++){link[p] = -1;}
    for(int q=0;q<10;q++){ht[q].empid = 0;}
    for(int r=0;r<10;r++){strcpy(ht[r].name," ");}
    cout <<"\nEnter number of employees you want to enter";
    cin>>x;
    for(int i=0;i<x;i++)
    {
        emp al;
        cout<<"\n enter employee ID";
        cin>>al.empid;
        cout<<"\n enter employee name";
        cin>>al.name;
        cout<<"\n enter employee salary";
        cin>>al.salary;
        enter (al);

    }


}
void ht::enter(emp x)
{
    int y = hash(x.empid);
    if(ht[y].empid == 0)
    {
        ht[y] = x;
    }
    else
    {
        int r = y;
        while(link[r] != -1)
        {
            r = link[r];
        }
        int p = r;
        do
        {
            r=((r+1)%10);
        }
        while(ht[r].empid != 0);
        if(hash(ht[p].empid) == 0)
        {
            link[p] = r;
        }
        ht[r] = x;
    }
}
void ht ::display()
{
    cout<<"\n"<<"S.No"<<"    "<<"Emoloyee ID"<<"    "<<"Employee Name"<<"    "<<"Salary"<<"    "<<"link";
    for (int i=0;i<10;i++)
    {
        if(ht[i].empid !=0)
        {

        cout<<"\n"<<i <<"    "<<ht[i].empid<<"     "<<ht[i].name<<"     "<<ht[i].salary<<"     "<<link[i];
        }

    else
    {
        cout<<"\n--    ------    ------    ------    ------";
    }
    }



}

int main()
{
    ht h;
    char ch;
    int c;
    do
    {
        cout<<"\n What do you want to do?";
        cout<<"\n 1.Enter employee information";
        cout<<"\n 2.Enter new emplyee";
        cout<<"\n 3.Display";
        cout<<"\n Enter choice";
        cin>>c;
        switch(c)
        {
            case 1:
            h.insert();
            break;
            case 2:
            emp a;
            cout<<"\nEnter employee ID";
            cin>>a.empid;
            cout<<"\nEnter name";
            cin>>a.name;
            cout<<"\nEnter salary";
            cin>>a.salary;
            h.enter(a);
            break;
            case 3:
            h.display();
            break;
        }
        cout<<"\nDo you want to continue?(y/n) ";
        cin>>ch;


    }while(ch == 'y'||ch =='Y');
    cout << "Hello world!" << endl;
    return 0;
}

No comments:

Post a Comment

Perform a suitable assignment using Xen Hypervisor or equivalent open source to configure it. Give necessary GUI.

 To install kvm on Fedora:  yum install kvm  yum install virt-manager libvirt libvirt-python python-virtinst  su -c "yum install @v...