#include<iostream>
using namespace std;
class Hash
{
int BUCKET;
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;
}
}
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;
}
}
}
void deleteItem(int key)
{
int index = hashFunction(key);
for (int i = 0; i < BUCKET; i++)
{
if (table[index][i] == key)
{
table[index][i] = 0;
break;
}
}
}
bool searchItem(int key)
{
int index = hashFunction(key);
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;
}
int hashFunction(int x)
{
return (x % BUCKET);
}
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;
}
}
};
int main()
{
int a[] = { 15, 11, 27, 8, 12 };
int n = sizeof(a) / sizeof(a[0]);
Hash h(7);
for (int i = 0; i < n; i++)
h.insertItem(a[i]);
h.deleteItem(12);
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