Hashing
Hashing
• In data structures,
1. There are several searching techniques like linear search,
binary search, search trees etc.
2. In these techniques, time taken to search any particular
element depends on the total number of elements.
a) Linear Search takes O(n) time to perform the search in
unsorted arrays consisting of n elements.
b) Binary Search takes O(logn) time to perform the search in
sorted arrays consisting of n elements.
c) It takes O(logn) time to perform the search in Binary Search
Tree consisting of n elements.
• Drawback-
1. As the number of elements increases, time taken to
perform the search also increases.
2. This becomes problematic when total number of
elements become too large.
Hashing in Data Structure
• Hashing is a well-known technique to search any particular element
among several elements.
• It minimizes the number of comparisons while performing the search.
Advantage
• Unlike other searching techniques,
• Hashing is extremely efficient.
• The time taken by it to perform the search does not
depend upon the total number of elements.
• It completes the search with constant time complexity
O(1).
Hashing Mechanism
In hashing,
• An array data structure called as Hash table is used to store
the data items.
• Based on the hash key value, data items are inserted into the
hash table.
Hash Key Value
• Hash key value is a special value that serves as an index for a
data item.
• It indicates where the data item should be be stored in the
hash table.
• Hash key value is generated using a hash function.
Hash Function
• Hash function is a function that maps any big number or
string to a small integer value.
• Hash function takes the data item as an input and
returns a small integer value as an output.
• The small integer value is called as a hash value.
• Hash value of the data item is then used as an index for
storing it into the hash table.
Types of Hash Functions
There are various types of hash functions available such
as
1. Mid Square Hash Function
2. Division Hash Function
3. Folding Hash Function etc.,
It depends on the user which hash function he wants to
use.
Properties of Hash Function
The properties of a good hash function are-
• It is efficiently computable.
• It minimizes the number of collisions.
• It distributes the keys uniformly over the table.
Division Method
• The easiest and quickest way to create a hash value is
through division. The k-value is divided by M in this
hash function, and the result is used.
• Formula:
h(K) = k mod M
0 0
1 81 1
2
4 64 4
5 25
6 36 16
7
9 49 9
Open Addressing
In open addressing,
1. Unlike separate chaining, all the keys are stored inside
the hash table.
2. No key is stored outside the hash table.
Collision: (h1(k)+ih(2))mod11
Keys: 20, 34, 45, 70, 56