Linear Probing C++ Implementation

#include<iostream>
using namespace std;

class lprobing{
int count,cap,*a,key,pos,i;
public:
lprobing(int c){
cap = c;
a = new int[c];
for(int j=0;j<c;j++) a[j]=-1;
count=0;
}
void insert(int val);
void delete1(int val);
void display();
int Hash(int val);
int search(int val);
};

int lprobing::Hash(int val){
return val%cap;
}

void lprobing::insert(int val){
if(count==cap) {
cout<<"Over-Flow"<<endl;
return;
}
else{
key = Hash(val);
if(a[key]==-1){
a[key] = val;
cout<<"Inserted at "<<key<<endl;
count++;
return;
}else{
i = key + 1;
while(i!=key){
if(a[i]==-1){
a[i] = val;
cout<<"Inserted at "<<i<<endl;
count++;
return;
}else{
i++;
if(i==cap) i=0;
}
}
}
}
}

int lprobing::search(int val){
if(count==0) return -1;
else{
key = Hash(val);
if(a[key]==val) return key;
else{
i = key + 1;
while(i!=key){
if(a[i]==val) return i;
else{
i++;
if(i==cap) i=0;
}
}
}
}
return -2;
}

void lprobing::delete1(int val){
pos = search(val);
if(pos==-1) cout<<"Under-Flow"<<endl;
else if(pos==-2) cout<<"Key not found"<<endl;
else{
key = Hash(val);
a[pos]=-1; //deleted
count--;
i = pos;         // previous
int j = pos+1;   // current
while(j!=pos){
if(Hash(a[j])==key){
int temp = a[j];
a[j] = a[i];
a[i] = temp;
i = j;
}
j++;
if(j==cap) j=0;
}
}
}

void lprobing::display(){
cout<<"\n-----------------------\nHash Table\n-----------------------\n";
for(i=0;i<cap;i++){
if(a[i]==-1) continue;
cout<<i<<"\t"<<a[i]<<endl;
}
cout<<endl;
}

int main(){
int ch,val,c,pos;
cout<<"Enter Table Size:";cin>>c;
lprobing obj(c);
do{
cout<<"1.Insert\n2.Delete\n3.Search\n4.Display\n5.Exit"<<endl;
cout<<"Enter your choice:";cin>>ch;
switch(ch){
case 1:
cout<<"Enter Element to insert:";cin>>val;
obj.insert(val);
break;
case 2:
cout<<"Enter Element to delete:";cin>>val;
obj.delete1(val);
break;
case 3:
cout<<"Enter Element to search:";cin>>val;
pos = obj.search(val);
if(pos==-2) cout<<"key not found"<<endl;
else if(pos==-1) cout<<"Table is Empty"<<endl;
else cout<<"Found at "<<pos<<endl;
break;
case 4:
obj.display();
break;
case 5:
break;
default:
cout<<"Re-Enter"<<endl;
}
}while(ch!=5);
}

Comments

Popular Posts