Wednesday, December 26, 2018

implementation of hash table


include<iostream>
using namespace std;
class hash
{
public:
int *a,sz,count;
hash(int n)
{
a=new int[sz=n];
for(int i=0;i<sz;i++)
{
a[i]=-1;
}
count=0;
}
void insert(int);
int delete1(int);
int search(int);
void display();
};
void hash::insert(int x)
{
if(count==sz)
{
cout<<"\n hash table is full ";
}
else
{
int key=x%sz;
int t=key;
if(a[key]==-1)
{
a[key]=x;
count++;
cout<<"\n"<<x<<"element inserted at "<<key+1;
}
else
{
xyz:
if(key==sz-1)
key=-1;
key=key+1;
if(key==t)
{
return ;
}
else
{
if(a[key]==-1)
{
a[key]=x;
count++;
cout<<"\n"<<x<<"element inserted at "<<key+1;
return ;
}
}
goto xyz;
}
}
}
int hash::delete1(int m)
{
int i;
int key=m%sz;
if(count==0)
{
return 0;
}
if(a[key]==m)
{
a[key]=-1;
count--;
return key+1;
}
else
{
for ( i=0;i<sz;i++)
{
if(a[i]==m)
{
a[i]=-1;
count--;
return i+1;
}
}
if(i == sz)
{
return 100;
}
}
}
int hash::search(int m)
{
int i;
int key=m%sz;
if(count==0)
{
return 0;
}
if(a[key]==m)
{
return key+1;
}
else
{
for (i=0;i<sz;i++)
{
if(a[i]==m)
{
return i+1;
}
}
if(i==sz)
{
return 100;
}
}
}
void hash::display()
{
for(int i=0;i<sz;i++)
{
if(a[i]!=-1)
{
cout<<"\n"<<i+1<<" "<<a[i];
}
}
}
int main()
{
int n,x,y,z,ch,fg;
cout<<"\n enter the size of hash table : \n";
cin>>n;
hash ob(n);
while(1)
{
cout<<"\n 1.insert\n2.delete\n3.search\n4.display\n5.exit\n enter your choice : ";
cin>>ch;
switch(ch)
{
case 1:
cout<<"\n enter an element to insert \n:";
cin>>x;
ob.insert(x);
break;
case 2:
cout<<"\n enter an element to delete \n :";
cin>>y;
fg=ob.delete1(y);
if(fg==100)
{
cout<<"element not in list\n ";
}
else if(fg==0)
{
cout<<"\n hash table is empty \n ";
}
else
{
cout<<"\n deleted element "<<y<<"at position"<<fg<<"\n";
}
break;
case 3:
cout<<"\n enter an element to search \n :";
cin>>z;
fg=ob.search(z);
if(fg==100)
{
cout<<"element not in list\n ";
}
else if(fg==0)
{
cout<<"\n hash table is empty \n ";
}
else
{
cout<<"\n"<<z<<"element searched at position "<<fg<<"\n";
}
break;
case 4:
ob.display();
break;
case 5:
exit(0);
default : cout<<"\n wrong choice \n";
}
}
return 0;
}
OUTPUT


Labels:

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home