C++: Create a class called \"HashTable\" This class will implement hashing on an
ID: 3779230 • Letter: C
Question
C++:
Create a class called "HashTable"
This class will implement hashing on an array of integers
Make the table size 11
Implement with linear probing. The hash function should be: h(x) = x % 11
Create search(), insert() and delete() member functions. Search should return the index of where the target is located, insert should allow the user to insert a value, and delete removes the desired value from the table.
In main perform the following:
1. Insert: 17 11 5 20 10 22 33 45
2. Print out the contents of the hash table (hint: I would make a member function for this)
3. Search for 11, then search for 45 and then search for 26
4. Delete 11
5. Search for 33
Every time you search for something, output it to the console.
Explanation / Answer
C++ Code :
#include <iostream>
using namespace std;
class HashTable{
public:
int hash[11]={0,0,0,0,0,0,0,0,0,0,0};
int hashFunction(int a){
return a%11;
}
int search(int a){
for(int i=0;i<11;i++){
if(a== hash[i]){
return i;
}
}
return -1;
}
void insert(int index, int value){
int i=0;
if(hash[index]==0){
hash[index] = value;
}
else {
while(i<11){
index++;
if(hash[index%11] == 0){
hash[index]=value;
return;
}
i++;
}
}
}
void deleteValue(int value){
for(int i=0;i<11;i++){
if(hash[i] == value){
hash[i] = 0;
cout << "value deleted :";
cout << value ;
cout << " ";
break;
}
}
}
};
int main()
{
HashTable ht;
ht.insert(ht.hashFunction(17),17);
ht.insert(ht.hashFunction(11),11);
ht.insert(ht.hashFunction(5),5);
ht.insert(ht.hashFunction(20),20);
ht.insert(ht.hashFunction(10),10);
ht.insert(ht.hashFunction(22),22);
ht.insert(ht.hashFunction(33),33);
ht.insert(ht.hashFunction(45),45);
for(int i=0;i<11;i++){
cout << ht.hash[i];
cout << " ";
}
cout << " ";
cout << "Found at Index :";
cout << ht.search(11);
cout << " Found at Index :";
cout << ht.search(45);
cout << " Found at Index :";
cout << ht.search(26);
cout << " ";
ht.deleteValue(11);
cout << " Found at Index :";
cout << ht.search(33);
cout << " ";
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.