Unit-5 Hashing
Unit-5 Hashing
INTRODUCTION TO HASHING
Hashing is the process of indexing and retrieving element (data) in a data structure to
provide a faster way of finding the element using a hash key.
Additionally, the hash function should produce a unique hash code for
each input, which is known as the hash property.
1. Division Method:
This is the most simple and easiest method to generate a hash value. The hash
function divides the value k by M and then uses the remainder obtained.
Formula:
h(K) = k mod M
Here,
k is the key value, and
M is the size of the hash table.
It is best suited that M is a prime number as that can make sure the keys are more
uniformly distributed. The hash function is dependent upon the remainder of a
division.
Example:
k = 12345
M = 95
h(12345) = 12345 mod 95
= 90
k = 1276
M = 11
h(1276) = 1276 mod 11
=0
Example:
k = 12345
k1 = 12, k2 = 34, k3 = 5
s = k1 + k2 + k3
= 12 + 34 + 5
= 51
h(K) = 51
Note:
The number of digits in each part varies depending upon the size of the hash table.
Suppose for example the size of the hash table is 100, then each part must have two
digits except for the last part which can have a lesser number of digits.
4. Multiplication Method
This method involves the following steps:
1. Choose a constant value A such that 0 < A < 1.
2. Multiply the key value with A.
3. Extract the fractional part of kA.
4. Multiply the result of the above step by the size of the hash table i.e. M.
5. The resulting hash value is obtained by taking the floor of the result obtained
in step 4.
Formula:
h(K) = floor (M (kA mod 1))
Here,
M is the size of the hash table.
k is the key value.
A is a constant value.
Example:
k = 12345
A = 0.357840
M = 100
h(12345) = floor[ 100 (12345*0.357840 mod 1)]
= floor[ 100 (4417.5348 mod 1) ]
= floor[ 100 (0.5348) ]
= floor[ 53.48 ]
= 53
example: We have given a hash function and we have to insert some elements in the hash table
using a separate chaining method for collision resolution technique.
Let’s see step by step approach to how to solve the above problem:
2) Open Addressing
In open addressing, all elements are stored in the hash table
itself. Each table entry contains either a record or NIL. When searching for an
element, we examine the table slots one by one until the desired element is found
or it is clear that the element is not in the table.