In: Computer Science
Implement one of the hashing procedures that we have discussed,
and the following related functions:
Make sure that your program correctly handles collisions and full hash table!
ANSWER :
Given related functions:-
(you dont mention any spwcific program ,so i answered in c++)
The program for the implementation of the HashTable is as below
HashTbl.cpp
#include<istream>
#include<cstdlib>
#include<string>
#include<cstdio>
using namespace std;
const int SIZE_OF_TBL = 128;
class HashTbl
{
public:
int keys;
int val;
HashTbl(int keys, int val)
{
this->keys = keys;
this->val = val;
}
};
class HashTblMapping
{
private:
HashTbl **tble;
public:
HashTblMapping()
{
tble = new HashTbl * [SIZE_OF_TBL];
for (int uu = 0; uu< SIZE_OF_TBL; uu++)
{
tble[uu] = NULL;
}
}
// Hashing functions
int HashF(int keys)
{
return keys % SIZE_OF_TBL;
}
//Inserting values using Hashes
void HashValuesInsert(int keys, int val)
{
int hs = HashF(keys);
while (tble[hs] != NULL && tble[hs]->keys != keys)
{
hs = HashF(hs + 1);
}
if (tble[hs] != NULL)
delete tble[hs];
tble[hs] = new HashTbl(keys, val);
}
//Searching for the elements using keys
int Find(int keys)
{
int hs = HashF(keys);
while (tble[hs] != NULL && tble[hs]->keys != keys)
{
hs = HashF(hs + 1);
}
if (tble[hs] == NULL)
return -1;
else
return tble[hs]->val;
}
// Deleting element using the keys
void Delete(int keys)
{
int hs = HashF(keys);
while (tble[hs] != NULL)
{
if (tble[hs]->keys == keys)
break;
hs = HashF(hs + 1);
}
if (tble[hs] == NULL)
{
cout<<"Elements was not found using the keys:
"<<keys<<endl;
return;
}
else
{
delete tble[hs];
}
cout<<"Element is successfully
deleted...."<<endl;
}
~HashTblMapping()
{
for (int uu = 0; uu < SIZE_OF_TBL; uu++)
{
if (tble[uu] != NULL)
delete tble[uu];
delete[] tble;
}
}
};
// Driver program
int main()
{
HashTblMapping hs;
int keys, val;
int ch;
while (1)
{
cout<<"\n----------------------"<<endl;
cout<<"Implementation Of HashTable"<<endl;
cout<<"\n----------------------"<<endl;
cout<<"1. Inserting Elements Using Keys"<<endl;
cout<<"2. Finding Elements Using Keys"<<endl;
cout<<"3. Deleting Elements Using Keys"<<endl;
cout<<"4.Exit"<<endl;
cout<<"Please enter a valid selection: ";
cin>>ch;
switch(ch)
{
case 1:
cout<<"Please enter the element to be inserted: ";
cin>>val;
cout<<"Please enter keys at which the element is to be
inserted: ";
cin>>keys;
hs.HashValuesInsert(keys, val);
break;
case 2:
cout<<"Please enter the keys which you want to search:
";
cin>>keys;
if (hs.Find(keys) == -1)
{
cout<<"No particular element was
found...."<<keys<<endl;
continue;
}
else
{
cout<<"Element found using keys: "<<keys<<" :
";
cout<<hs.Find(keys)<<endl;
}
break;
case 3:
cout<<"Please enter the element of the keys to be deleted:
";
cin>>keys;
hs.Delete(keys);
break;
case 4:
exit(1);
default:
cout<<"\nInvalid Option.....Try entering valid
option.\n";
}
}
return 0;
}
Output: