Chapter 13 Hashing
Chapter 13 Hashing
1
Why Hashing?
The preceding chapters introduced search trees. An element can be
found in O(logn) time in a well-balanced search tree. Is there a more
efficient way to search for an element in a container? This chapter
introduces a technique called hashing. You can use hashing to
implement a map or a set to search, insert, and delete an element in
O(1) time.
2
Map
A map is a data structure that stores entries. Each entry contains two
parts: key and value. The key is also called a search key, which is
used to search for the corresponding value. For example, a
dictionary can be stored in a map, where the words are the keys and
the definitions of the words are the values.
3
What is Hashing?
If you know the index of an element in the array, you can retrieve
the element using the index in O(1) time. So, can we store the
values in an array and use the key as the index to find the value?
The answer is yes if you can map a key to an index.
The array that stores the values is called a hash table. The function
that maps a key to an index in the hash table is called a hash
function.
4
Hash Function and Hash Codes
A typical hash function first converts a search key to an integer
value called a hash code, and then compresses the hash code into
an index to the hash table.
5
Linear Probing Animation
6
Quadratic Probing
7
Double Hashing
h’(k) = 7 – k % 7;
8
Handling Collisions Using Separate Chaining
The separate chaining scheme places all entries with the same hash
index into the same location, rather than finding new locations.
Each location in the separate chaining scheme is called a bucket.
A bucket is a container that holds multiple entries.
9
Implementing Map Using Hashing
10
Implementing Set Using Hashing
11