Last active
July 8, 2019 08:20
-
-
Save manojnaidu619/5d945e9c41090b7ff6b0a395f9a07d9f to your computer and use it in GitHub Desktop.
Linear Probing (Insertion and Searching) in CPP
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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