Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Create a hash table class/struct. Define an array that holds 27 elements. Define

ID: 3823007 • Letter: C

Question

Create a hash table class/struct.

Define an array that holds 27 elements.

Define a function called Hash(int)

-This function returns the modulo of that int by the size of the table (array).

Define an add function that takes an integer.

-This function takes the integer, determines the hash of that number by calling the above hash function, then adds it to the table using linear probing for collision resolution.

Define a function that looks up a value, it takes an integer, return -1 if the value is not in the table.

Create a main that allows the user to add and lookup items in the table.

Please write in C++. Thumbs up if everything is correct. Thanks.

Explanation / Answer

#include <iostream>
#include <stdlib.h>
#define tableSize 27
using namespace std;

int hashTable[tableSize];

int Hash(int n)
{
return n%tableSize;
}


void add(int n)
{
int index = Hash(n);
  
int count = 0;
while(count < tableSize)
{
if (hashTable[index] == -1)
{
hashTable[index] = n;
break;
}
else
{
index = (index + 1) % tableSize;
count++;
}
}
}

void printArray()
{
for(int i = 0; i < tableSize; i++)
{
cout << hashTable[i] << " ";
}
cout << endl;
}

int lookup(int n)
{
int index = Hash(n);
  
int count = 0;
while(count < tableSize)
{
if (hashTable[index] == n)
{
return n;
}
else
{
index = (index + 1) % tableSize;
count++;
}
}
return -1;
}

int main()
{
for(int i = 0; i < tableSize; i++)
{
hashTable[i] = -1;
}

while(true)
{
cout << "Choose from given menu: " << endl;
cout << "1. Add element to hash." << endl;
cout << "2. Lookup value in hash" << endl;
cout << "Any other key to quit" << endl;
int choice;
cin >> choice;
if(choice == 1)
{
cout << "Enter number to be added: ";
int n;
cin >> n;
add(n);
}
else if (choice == 2)
{
cout << "Enter number to be searched: ";
int n;
cin >> n;
if(lookup(n) != -1)
{
cout << " Found" << endl;
}
else
{
cout << " Not found." << endl;
}
}
else
{
break;
}
}
return 0;
}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote