HASH SEARCH
Hash table
Hash Table is a data structure which store data in
associative manner. In hash table, data is stored
in array format where each data values has its
own unique index value. Access of data becomes
very fast if we know the index of desired data.
Hashing
Hashing is a technique to convert a range of key values
into a range of indexes of an array. We're going to use
modulo operator to get a range of key values. Consider an
example of hashtable of size 20, and following items are
to be stored. Item are in key, value format.
Hashing
Consider an example of hashtable of size 20, and following items are to be
stored. Item are in key, value format.
1) 1, 20 2) 2, 70 3) 42, 80
4) 4, 25 5) 12, 44 6) 14, 32
7) 17, 11 8) 13, 78 9) 37, 98
S.n. Key Hash Array Index
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
S.n. Key Hash Array Index
1 1 1 % 20 = 1 1
2 2 2 % 20 = 2 2
3 42 42 % 20 = 2 3
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 18
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
1 2 42 4 12 13 14 17 37
Value index
Example : 24,48 0
Collision 91,67 1
Search
Key(24,52,91,67,48,83) 2
Hash Table 3
Hash function(K mod 10, k 52 4
mod n, mid square, folding 83 5
method
6
K mod n =6 method used
and place the key in the 7
table 8
Eg : 24%6 = 4 9
Linear probing
Linear probing is a scheme in computer programming for
resolving collisions in hash tables, If a hash function maps two
keys to the same position in the hash table, then a collision
occurs.
S.n. Key Hash Array Index
2 2 2 % 20 = 2 2
3 42 42 % 20 = 2 2
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.
S.n. Key Hash Array Index
2 2 2 % 20 = 2 2
3 42 42 % 20 = 2 3
Searching using hash
table
Whenever an element is to be searched, compute the
hash code of the key passed and locate the element
using that hash code as index in the array. Use linear
probing to get the element ahead if the element is not
found at the computed hash code.
Value index
Example : 0
91 1
Search
Key(24,52,91,67,48,83) 52 2
Hash Table 83 3
Hash function(K mod 10, k 24 4
mod n, mid square, folding 5
method
6
K mod 10 method used
and place the key in the 67 7
table 48 8
Eg : 24%10 = 4 9
Various Hash
Functions
Division hash function
1. convert key to a positive integer
2. return the integer modulo the table size
Mid-square hash function
1. convert key to an integer
2. multiply the integer by itself
3. return several digits in the middle of result •
Multiplicative hash function
1. convert the key to an integer
2. multiply the integer by a constant less than 1
3. return the first several digits of the fractional part