Hashing
Hashing
Hashing refers to the process of generating a fixed-size output from an input of variable size
using the mathematical formulas known as hash functions. This technique determines an index or
location for the storage of an item in a data structure.
Hashing in Data Structures refers to the process of transforming a given key to another value. It
involves mapping data to a specific index in a hash table using a hash function that enables fast
retrieval of information based on its key. The transformation of a key to the corresponding value
is done using a Hash Function and the value obtained from the hash function is called Hash Code
.
There are many hash functions that use numeric or alphanumeric keys.
1. Division Method
The division method involves dividing the key by a prime number and using the remainder as the
hash value.
h(k)=k mod m
3. Mid-Square Method
In the mid-square method, the key is squared, and the middle digits of the result are taken as the
hash value.
Steps:
1. Square the key.
2. Extract the middle digits of the squared value.
4. Folding Method
The folding method involves dividing the key into equal parts, summing the parts, and then
taking the modulo with respect to 𝑚m.
Steps:
1. Divide the key into parts.
2. Sum the parts.
3. Take the modulo 𝑚m of the sum.
The first hash function is h1(k) which takes the key and gives out a location on the
hash table. But if the new location is not occupied or empty then we can easily
place our key.
But in case the location is occupied (collision) we will use secondary hash-function
h2(k) in combination with the first hash-function h1(k) to find the new location on
the hash table.
● Chaining: Store colliding keys in a linked list or binary search tree at each index
● Cuckoo Hashing: Use multiple hash functions to distribute keys