21 - Data Structure and Algorithms - Hash Table
21 - Data Structure and Algorithms - Hash Table
Hash Table
Thus, it becomes a data structure in which insertion and search operations are
very fast irrespective of the size of the data. Hash Table uses an array as a
storage medium and uses hash technique to generate an index where an
element is to be inserted or is to be located from.
Hashing
(1,20)
(2,70)
(42,80)
(4,25)
(12,44)
(14,32)
(17,11)
(13,78)
(37,98)
1 1 1 % 20 = 1 1
2 2 2 % 20 = 2 2
3 42 42 % 20 = 2 2
4 4 4 % 20 = 4 4
5 12 12 % 20 = 12 12
6 14 14 % 20 = 14 14
7 17 17 % 20 = 17 17
8 13 13 % 20 = 13 13
9 37 37 % 20 = 17 17
Linear Probing
As we can see, it may happen that the hashing technique is used to create an
already used index of the array. In such a case, we can search the next empty
location in the array by looking into the next cell until we find an empty cell.
This technique is called linear probing.
After Linear Probing, Array
Sr.No. Key Hash Array Index
Index
1 1 1 % 20 = 1 1 1
2 2 2 % 20 = 2 2 2
3 42 42 % 20 = 2 2 3
4 4 4 % 20 = 4 4 4
5 12 12 % 20 = 12 12 12
6 14 14 % 20 = 14 14 14
7 17 17 % 20 = 17 17 17
8 13 13 % 20 = 13 13 13
9 37 37 % 20 = 17 17 18
Basic Operations
Define a data item having some data and key, based on which the search is to
be conducted in a hash table.
struct DataItem {
int data;
int key;
};
Hash Method
Define a hashing method to compute the hash code of the key of the data item.
Search Operation
Example
while(hashArray[hashIndex] != NULL) {
if(hashArray[hashIndex]->key == key)
return hashArray[hashIndex];
++hashIndex;
hashIndex %= SIZE;
return NULL;
Insert Operation
Example
void insert(int key,int data) {
item->data = data;
item->key = key;
++hashIndex;
hashIndex %= SIZE;
hashArray[hashIndex] = item;
Delete Operation
Whenever an element is to be deleted, compute the hash code of the key
passed and locate the index using that hash code as an index in the array. Use
linear probing to get the element ahead if an element is not found at the
computed hash code. When found, store a dummy item there to keep the
performance of the hash table intact.
Example
while(hashArray[hashIndex] !=NULL) {
if(hashArray[hashIndex]->key == key) {
hashArray[hashIndex] = dummyItem;
return temp;
}
//go to next cell
++hashIndex;
hashIndex %= SIZE;
return NULL;