DS Module 5 Hashing
DS Module 5 Hashing
Hashing
Priority queues
Hashing
• Hashing is a technique that is used to uniquely identify a
specific object from a group of similar objects.
Some examples of how hashing is used in our lives include:
• In universities, each student is assigned a unique roll number
that can be used to retrieve information about them.
• In libraries, each book is assigned a unique number that can
be used to determine information about the book, such as its
exact position in the library or the users it has been issued to
etc.
• In both these examples the students and books were hashed
to a unique number.
Hashing
• Hashing is a technique or process of mapping keys, and values into
the hash table by using a hash function.
• It is done for faster access to elements.
1. Division Method.
2. Mid Square Method.
3. Folding Method.
4. Digit Analysis
5. Converting keys to integers
Division Method
• This is the most simple and easiest method to generate a hash
value. The hash function divides the value k by N and then
uses the remainder obtained.
• Formula: h(K) = k mod N
• Here, k is the key value, and N is the size of the hash table.
• It is best suited that N 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.
• k = 12345, N = 95
h(12345) = 12345 mod 95 = 90
• k = 1276 , N = 11
h(1276) = 1276 mod 11 = 0
Mid Square Method
The mid-square method is a very good hashing method. It
involves two steps to compute the hash value-
1. Square the value of the key k i.e. k2
2. Extract the middle r digits as the hash value.
[0] function
[1]
[2] for
[3] do
[4] while
[5]
[6]
[7]
[8]
[9] else
[10]
[11]
[12] if
Linear probing
element *search(int k)
{
int hBucket, cBucket;
hBucket = h(k);
for(cBucket =hBucket; ht[cBucket] && ht[cBucket]->key!=k; )
{
cBucket= (cBucket+1) % b;
if(cBucket== hBucket)
return NULL;
}
if( ht[cBucket]->key==k)
return ht[cBucket];
return NULL;
}
Chaining
[1] NULL
[3] define
[4] exp
[6] NULL
…
[26] NULL
Single ended and Double ended priority
queues
• A priority queue is a collection elements with each
element has an associated priority.