Professional Documents
Culture Documents
Hashing
Hashing
1
Tables: rows & columns of information
2
Tables: rows & columns of information
3
Tables: rows & columns of information
4
The Table ADT: operations
5
How should we implement a table?
7
Implementation 1: unsorted sequential array
…
find: search through the keys and so on
one at a time, potentially all of
the keys; (n)
remove: find + replace
removed node with last node;
(n)
8
Implementation 2:sorted sequential array
…
remove: find, remove node and so on
and shuffle down; (n)
9
Searching an Array: Binary Search
10
Implementation 3: linked list
11
Implementation 4: AVL tree
and so on
12
Anything better?
13
Implementation 5: Hashing
An array in which
TableNodes are not stored key entry
consecutively
Their place of storage is
4
calculated using the key and
a hash function
10
hash array
Key index
function
123
Keys and entries are
scattered throughout the
array.
14
Hashing
15
Hashing
16
Example: fruits
20
Finding the hash function
21
Example Hash Functions
length −1 i
h( str ) = ∑ str[i ] × b %T
i =0
= 0
+
Example : h( ABC ) (65b 66b 67b )%T
1
+ 2
22
Example Hash Functions
23
Collision
25
Solution for Handling collisions
26
Solution for Handling collisions
27
Solution for Handling collisions
28
Solution 1: Open Addressing
30
Linear Probing: insert
32
Linear Probing: insert
Suppose: ...
• You want to add cardinal to 141
this hash table 142 robin
• hashCode(“cardinal”) = 147
143 sparrow
• The last location is 148
144 hawk
• 147 and 148 are occupied
145 seagull
Solution:
146
• Treat the table as circular;
147 bluejay
after 148 comes 0
• Hence, cardinal goes in 148 owl
location 0 (or 1, or 2, or ...)
33
Linear Probing: find
35
Clustering
key entry
123
38
Collision resolution: chaining
39
Applications of Hashing
40
Applications of Hashing
41
When is hashing suitable?
42