Hash Functions
Hash Functions
HASH FUNCTIONS
Hash Function
• Hashing is the transformation of a string of characters into a
usually shorter fixed-length value or key that represents the
original string.
• Truncation Method
• Mid square Method
• Folding Method
• Division Method
Truncation Method
0
1
2 2822 8232
3 2813 3553
4
5 1615 2125
6
7
8 4288
9
• Open addressing ensures that all elements are
stored directly into the hash table, thus it
attempts to resolve collisions using various
methods.
– Linear Probing resolves collisions by placing the data
into the next open slot in the table.
– Quadratic Probing-The i2 slot is searched in ith probe
– Double Hashing We use another hash function
hash2(x) and look for i*hash2(x) slot in i’th rotation
• Open Addressing
Like separate chaining, open addressing is a method for
handling collisions. In Open Addressing, all elements are
stored in the hash table itself. So at any point, size of the
table must be greater than or equal to the total number of
keys (Note that we can increase table size by copying old
data if needed).
0
1
2 2822
3 2813
4 3553 3553: h(3553)=3, rh(1)=4
5 1615
6 2125 2125: h(2125)=5, rh(1)=6
7 8232 8232: h(8232)=2, rh(2)=3,
rh(3)=4, rh(4)=5, rh(5)=6, rh(6)=7
8 4288
9
Open addressing -- quadratic Probing
• The jth rehash is hj(key) = (h(key)+j2) % array_size
• E.g., (input: 2822, 1615, 2813, 3553, 2125, 8232,4288)
0
8232: h(8232)=2, h 1=2+1=3,
1 8232 h 2=2+(2*2)=6, h3=(2+3*3)%10=1
2 2822
3 2813
4 3553 3553: h(3553)=3, h1=3+1=4
5 1615
6 2125 2125: h(2125)=5, h1=5+1=6
7
8 4288
9
Coalesced Hashing