#include<iostream>
using namespace std;
class Hash
{
int BUCKET; // No. of buckets
// Pointer to an array containing buckets
int **table;
public:
Hash(int V)
{
this->BUCKET = V;
table = new int*[BUCKET];
for (int i = 0; i < BUCKET; i++)
{
table[i] = new int[BUCKET];
for(int j = 0; j < BUCKET; j++)
table[i][j] = 0;
}
}
// inserts a key into hash table
void insertItem(int x)
{
int index = hashFunction(x);
for (int i = 0; i < BUCKET; i++)
{
if (table[index][i] == 0)
{
table[index][i] = x;
break;
}
}
}
// deletes a key from hash table
void deleteItem(int key)
{
int index = hashFunction(key);
// find the key in (index)th list
for (int i = 0; i < BUCKET; i++)
{
if (table[index][i] == key)
{
table[index][i] = 0;
break;
}
}
}
// search a key in hash table
bool searchItem(int key)
{
int index = hashFunction(key);
// find the key in (index)th list
for (int i = 0; i < BUCKET; i++)
{
if (table[index][i] == key)
{
return true;
}
}
return false;
}
int no_of_the_chains()
{
int res = 0;
for (int i = 0; i < BUCKET; i++)
{
if (table[i][0]!=0)
res++;
}
return res;
}
// hash function to map values to key
int hashFunction(int x)
{
return (x % BUCKET);
}
// function to display hash table
void displayHash()
{
for (int i = 0; i < BUCKET; i++)
{
cout << i;
for (int j = 0; j < BUCKET; j++)
{
if (table[i][j] == 0)
break;
cout << " --> " << table[i][j];
}
cout << endl;
}
}
};
// Driver program
int main()
{
// array that contains keys to be mapped
int a[] = { 15, 11, 27, 8, 12 };
int n = sizeof(a) / sizeof(a[0]);
// insert the keys into the hash table
Hash h(7); // 7 is count of buckets in
// hash table
for (int i = 0; i < n; i++)
h.insertItem(a[i]);
// delete 12 from hash table
h.deleteItem(12);
// display the Hash table
h.displayHash();
cout << "h.searchItem(11)= " << h.searchItem(11) << endl;
cout << "h.searchItem(12)= " << h.searchItem(12) << endl;
cout << "h.no_of_the_chains()= " << h.no_of_the_chains() << endl;
return 0;
}
Comments
Leave a comment