Skip to content

Instantly share code, notes, and snippets.

@manojnaidu619
Last active July 8, 2019 08:20
Show Gist options
  • Save manojnaidu619/5d945e9c41090b7ff6b0a395f9a07d9f to your computer and use it in GitHub Desktop.
Save manojnaidu619/5d945e9c41090b7ff6b0a395f9a07d9f to your computer and use it in GitHub Desktop.
Linear Probing (Insertion and Searching) in CPP
#include <iostream>
using namespace std;
int hash_(int key){
return key%10;
}
int insert_probe(int HT[],int key){
int i=1,pindex;
while(1){
pindex = (hash_(key)+i)%10; // (hash_(key)+i*i)%10 for Quadratic probing
if(HT[pindex] == 0){
return pindex;
}
i++;
}
}
int search_probe(int HT[], int key){
int i=1, pindex;
while(1){
pindex = (hash_(key)+i)%10; // (hash_(key)+i*i)%10 for Quadratic probing
if(HT[pindex] == 0){
return -1;
}else if(HT[pindex] == key){
return pindex;
}
i++;
}
}
void insert(int HT[], int key){
int index = hash_(key);
if(HT[index] == 0){
HT[index] = key;
}else{
int pindex = insert_probe(HT,key);
HT[pindex] = key;
}
}
void search(int HT[], int key){
int index = hash_(key);
int pindex;
if(HT[index] == key){
cout << endl << key << " found at : " << index << endl;
return;
}else{
pindex = search_probe(HT, key);
cout << endl;
pindex == -1 ? cout << " Not found!" : cout << key << " found at : " << pindex << endl;
}
}
int main(){
int HT[10] = {0};
insert(HT,10);
insert(HT,15);
insert(HT,25);
for(int i=0;i<10;i++){
cout << HT[i] << " ";
}
search(HT,25);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment