Hash Table
Hash Table
The Hash table data structure stores elements in key-value pairs where
Hash Collision
When the hash function generates the same index for multiple keys, there will
be a conflict (what value to be stored in that index). This is called a hash
collision.
We can resolve the hash collision using one of the following techniques.
Collision resolution by chaining
If j is the slot for multiple elements, it contains a pointer to the head of the list
of elements. If no element is present, j contains NIL .
chainedHashSearch(T, k)
return T[h(k)]
chainedHashInsert(T, x)
T[h(x.key)] = x //insert at the head
chainedHashDelete(T, x)
T[h(x.key)] = NIL
2. Open Addressing
Unlike chaining, open addressing doesn't store multiple elements into the
same slot. Here, each slot is either filled with a single key or left NIL .
i. Linear Probing
where
i = {0, 1, ….}
where,
If a collision occurs after applying a hash function h(k) , then another hash
function is calculated for finding the next slot.
h(k, i) = (h1(k) + ih2(k)) mod m
Here, we will look into different methods to find a good hash function
1. Division Method
If k is a key and m is the size of the hash table, the hash function h() is
calculated as:
h(k) = k mod m
For example, If the size of a hash table is 10 and k = 112 then h(k) =
112 mod 10 = 2 . The value of m must not be the powers of 2 . This is because
the powers of 2 in binary format are 10, 100, 1000, … . When we find k mod m ,
2. Multiplication Method
where,
#include <iostream>
#include <list>
using namespace std;
class HashTable
{
int capacity;
list<int> *table;
public:
HashTable(int V);
void insertItem(int key, int data);
void deleteItem(int key);
int checkPrime(int n)
{
int i;
if (n == 1 || n == 0)
{
return 0;
}
for (i = 2; i < n / 2; i++)
{
if (n % i == 0)
{
return 0;
}
}
return 1;
}
int getPrime(int n)
{
if (n % 2 == 0)
{
n++;
}
while (!checkPrime(n))
{
n += 2;
}
return n;
}
list<int>::iterator i;
for (i = table[index].begin();
i != table[index].end(); i++)
{
if (*i == key)
break;
}
if (i != table[index].end())
table[index].erase(i);
}
void HashTable::displayHash()
{
for (int i = 0; i < capacity; i++)
{
cout << "table[" << i << "]";
for (auto x : table[i])
cout << " --> " << x;
cout << endl;
}
}
int main()
{
int key[] = {231, 321, 212, 321, 433, 262};
int data[] = {123, 432, 523, 43, 423, 111};
int size = sizeof(key) / sizeof(key[0]);
HashTable h(size);
h.deleteItem(12);
h.displayHash();
}
cryptographic applications