So recently I had a quiz for my Data Structure subject, and there was a question involving hash tables. My lecturer did teach the theories behind it but never taught the way to code it which was extremely frustrating. I tried to google any info on how to do it, but to no avail. Now after the quiz, I just want to know how this is done so I can improve my knowledge for further tests or quizzes. I've also added my submission incase anyone needed to see it.
#include <iostream>
using namespace std;
int hash[30];
string key;
int value, keylength;
char yesorno;
int division(int keylength){
for(int i = 0; i <= keylength; i++){
value = keylength % 30;
hash[value];
cout << "The bucket/cell location : " << hash[value] << endl;
}
}
/*int hashing(int hash[], int value){
for(int k = 0; k <=30; k++){
hash[k] = value;
cout << "The bucket/cell location : " << hash[value] << endl;
}
}*/
int main(){
do {
cout << "Enter planet name : ";
cin >> key;
keylength == key.length();
division(keylength);
//hashing(hash, value);
cout << "Do you want to continue...? " << endl;
cout << "Press 'Y' or 'y' for Yes else 'N' or 'n' : ";
cin >> yesorno;
} while(yesorno = 'Y' || 'y');
return 0;
}
The question is not asking for storing int
into hash table but the value of position in hash table where key
(here planet names) is stored. Quadratic probing will be implemented somewhat like this:
Create hash value from key using division method
If hashtable[value]
is unoccupied then no need of any probing. We occupy it and return value. Else we will start quadratic probing like this:
for(int i=0;i<30;i++){ probe_value=(i*i+value)%30; // quadratic probing if(hashtable[probe_value] == "0"){ return probe_value; } } return -1; // as hashtabletable is full;
Complete program code:
#include<bits/stdc++.h>
using namespace std;
string hashtable[30];
int hashtableing(string key){
int value,probe_value;
value= (key.length())%30; //division
if(hashtable[value] == "0" || hashtable[value] ==key){
hashtable[value]=key;
return value;
}else{
for(int i=0;i<30;i++){
probe_value=(i*i+value)%30; // quadratic probing
if(hashtable[probe_value] == "0"){
return probe_value;
}
}
return -1; // as hashtabletable is full;
}
}
int main(){
string key;
char choice='Y';
for(int i=0;i<30;i++){
hashtable[i]="0"; //0 indicates cell is unoccupied for probing
}
while(choice != 'N' && choice !='n'){
cout<<"Enter planet name:"<<endl;
cin>>key;
cout<<"The bucket/cell location :"<< hashtableing(key)<<endl;
cout<<"Do you want to continue...?"<<endl;
cout<<"Press 'Y' or 'y' for Yes else 'n' or 'N':";
cin>>choice;
}
return 0;
}