Hash Table Implementation – Model 2


//  HASH TABLE IMPLEMENTATION

#include<iostream.h>
#include<conio.h>

#define SIZE 5

int hash[SIZE];
int search(int);
void insert(int x)
{
int s=search(x);
if(s>=0)
cout<<“\nThe element is already present in the hash table”;
else if(s==-2)
cout<<“\nHash table is full”;
else  //s equal to -1
{
int h=x%SIZE;
if(hash[h]==NULL) hash[h]=x;
else
{
int t=h;
h=(x+1)%SIZE;
for(int i=2;hash[h]!=NULL && h!=t ;i++)
h=(x+i)%SIZE;
if(h!=t)
{
hash[h]=x;
cout<<“\nThe given element is inserted”;
}
}
}
}
void delet(int x)
{
int s=search(x);
if(s>=0)
{
hash[s]=NULL;
cout<<“\nThe given element is deleted”;
}
else
cout<<“\nThe element is not present in the table.”;
}

int search(int x)
{
int h=x%SIZE;
if(hash[h]==NULL) return -1;
else if(hash[h]==x) return h;
else
{
int t=h;
h=(x+1)%SIZE;
for(int i=2; h!=t ;i++)
{
if(hash[h]==NULL) return -1;
else if(hash[h]==x) return h;
else
h=(x+i)%SIZE;
}
return -2;
}
}

void display()
{
cout<<“Hash table contents is”;
for(int i=0;i<SIZE;i++)
cout<<“\n”<<i<<“\t”<<hash[i];
}
void main()
{
clrscr();
for(int i=0;i<SIZE;i++)
hash[i]=NULL;
int c,x,h;
while(1)
{
cout<<“\n1.Insert 2.Delete 3.Search 4.Display 5.Exit”;
cout<<“\nEnter your choice:”;
cin>>c;
switch(c)
{
case 1:
cout<<“Enter the element to be inserted:”;
cin>>x;
insert(x);
break;
case 2:
cout<<“Enter the element to be deleted:”;
cin>>x;
delet(x);
break;
case 3:
cout<<“Enter the element to be searched:”;
cin>>x;
int s=search(x);
if(s>=0) cout<<“Element is present at position “<<s;
else
cout<<“Element is not present”;
break;
case 4:
display();
break;
case 5:
return;
}
}
}

Advertisements