2. Hashing
• General Idea
• Advantages
• Hash Function
• Collisions
• Collision Resolution Techniques
• Separate Chaining
• Linear Chaining
• Quadratic Probing
• Double Hashing
• Application
Implementation of Dictionaries
3. Introduction
• 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.
4. Continue…
• Assume that you have an object and you want to assign a key to it to
make searching easy. To store the key/value pair, you can use a simple
array like a data structure where keys (integers) can be used directly as
an index to store values.
• However, in cases where the keys are large and cannot be used directly
as an index, you should use hashing.
5. Continue…
• In hashing, largekeys are converted into small keys by using hash
functions.
• The values are then stored in a data structure called hash table.
• The idea of hashing is to distribute entries (key/value
pairs)
uniformly across an array.
• Each element is assigned a key (converted key).
• By using that key you can access the element in O(1) time. Using the key,
the algorithm (hash function) computes an index that suggests where an
6. Continue…
• Hashing is implemented in two steps:
• An element is converted into an integer by using a hash function. This element
can be used as an index to store the original element, which falls into the hash
table.
• The element is stored in the hash table where it can be quickly retrieved using
hashed key.
• hash = hashfunc(key) index =
hash % array_size
7. Advantages
• The main advantage of hash tables over other table data structures is
speed.
• This advantage is more apparent when the number of entries is large
(thousands or more).
• Hash tables are particularly efficient when the maximum number of
entries can be predicted in advance, so that the bucket array can be
allocated once with the optimum size and never resized.
8. Hash function
• A hash function is any function that can be used to map a data set
of an arbitrary size to a data set of a fixed size, which falls into the hash
table.
• The values returned by a hash function are called hash values, hash codes,
hash sums, or simply hashes.
9. Continue…
• A hash function is any function that can be used to map a data set of an arbitrary
size to a data set of a fixed size, which falls into the hash table.
• The values returned by a hash function are called hash values, hash codes, hash
sums, or simply hashes.
• To achieve a good hashing mechanism, It is important to have a good hash
function with the following basic requirements:
• Easy to compute
• Uniform distribution
• Less Collision
10. Different Hash functions
Division Method
• It is the most simple method of hashing an integer x. This method divides x by M
and then uses
• the remainder obtained. In this case, the hash function can be given as
h(x) = x mod M
Example:
• Calculate the hash values of keys 1234 and 5462.
Solution Setting M = 97, hash values can be calculated as:
h(1234) = 1234 % 97 = 70
h(5642) = 5642 % 97 = 16
11. Continue…
• Multiplication Method
The steps involved in the multiplication method are as follows:
Step 1: Choose a constant A such that 0 < A < 1.
Step 2: Multiply the key k by A.
Step 3: Extract the fractional part of kA.
Step 4: Multiply the result of Step 3 by the size of hash table (m).
Hence, the hash function can be given as:
h(k) = abs(m (kA mod 1) )
• where (kA mod 1) gives the fractional part of kA and m is the total number of
indices in the hash table.
12. Continue…
Example:
Given a hash table of size 1000, map the key 12345 to an appropriate
location in the hash table.
Solution We will use A = 0.618033, m = 1000, and k = 12345
h(12345) = abs(1000 (12345 ¥ 0.618033 mod 1))
h(12345) = abs(1000 (7629.617385 mod 1) )
h(12345) = abs( 1000 (0.617385) )
h(12345) = abs(617.385)
h(12345) = 617
13. Continue…
Mid-Square Method
The mid-square method is a good hash function which works in two steps:
Step 1: Square the value of the key. That is, find k2.
Step 2: Extract the middle r digits of the result obtained in Step 1.
Example:
Calculate the hash value for keys 1234 and 5642 using the mid-square method. The hash table has
100 memory locations.
Solution:
Note that the hash table has 100 memory locations whose indices vary from 0 to 99.
This means that only two digits are needed to map the key to a location in the hash table, so r = 2.
When k = 1234, k2 = 1522756, h (1234) = 27
When k = 5642, k2 = 31832164, h (5642) = 21
14. Continue…
Folding Method
The folding method works in the following two steps:
Step 1: Divide the key value into a number of parts. That is,
divide k into parts k1, k2, ..., kn, where each part has the same
number of digits except the last part which may have lesser digits
than the other parts.
Step 2: Add the individual parts. That is, obtain the sum of k1 + k2 + ...
+ kn. The hash value is produced by ignoring the last carry, if any.
15. Continue…
Example:
Given a hash table of 100 locations, calculate the hash value
using folding method for keys 5678, 321, and 34567.
Solution
Since there are 100 memory locations to address, we will break
the key into parts where each part (except the last) will contain two
digits. The hash values can be obtained as shown below:
17. Collisions
• collisions occur when the hash function maps two different keys to
the same location. Obviously, two records cannot be stored in the
same location.
• Therefore, a method used to solve the problem of collision, also called
collision resolution technique, is applied.
• The two most popular methods of resolving collisions are:
1. Open addressing
2. Chaining
18. Open addressing
• Choosing a hash function that minimizes the number of collisions
and also hashes uniformly is another critical issue.
• We use in open addressing:
• Linear probing (closed hashing)
• Quadratic Probing
• Double hashing
19. Linear Probing
• In open addressing, instead of in linked lists, all entry records are
stored in the array itself.
• When a new entry has to be inserted, the hash index of the hashed
value is computed and then the array is examined (starting with the
hashed index).
• If the slot at the hashed index is unoccupied, then the entry record is
inserted in slot at the hashed index else it proceeds in some probe
sequence until it finds an unoccupied slot.
20. Continue....
• The probe sequence is the sequence that is followed while traversing
through entries. In different probe sequences, you can have different
intervals between successive entry slots or probes.
• When searching for an entry, the array is scanned in the same
sequence until either the target element is found or an unused slot is
found. This indicates that there is no such key in the table. The name
"open addressing" refers to the fact that the location or address of the
item is not determined by its hash value.
21. Continue....
• Linear probing is when the interval between successive probes is
fixed (usually to 1). Let’s assume that the hashed index for a particular
entry is index. The probing sequence for linear probing will be:
index = index % hashTableSize
index = (index + 1) % hashTableSize
index = (index + 2) % hashTableSize
index = (index + 3) % hashTableSize
22. Quadratic Probing
• Quadratic probing is similar to linear probing and the only difference
is the interval between successive probes or entry slots.
• Here, when the slot at a hashed index for an entry record is already
occupied, you must start traversing until you find an unoccupied slot.
• The interval between slots is computed by adding the successive
value of an arbitrary polynomial in the original hashed index.
23. Continue....
• Let us assume that the hashed index for an entry is index and at
index there is an occupied slot. The probe sequence will be as follows:
24. Double Hashing
• Double hashing is similar to linear probing and the only difference is
the interval between successive probes. Here, the interval between
probes is computed by using two hash functions.
• Let us say that the hashed index for an entry record is an index that is
computed by one hashing function and the slot at that index is already
occupied. You must start traversing in a specific probing sequence to
look for an unoccupied slot. The probing sequence will be:
index = (index + 1 * indexH) % hashTableSize;
index = (index + 2 * indexH) % hashTableSize;
25. Separate Chaining (Open Hashing)
• Separate chaining is one of the most commonly used collision
resolution techniques.
• Itis usually implemented using linked lists. In separate chaining,
each element of the hash table is a linked list.
• To store an element in the hash table you must insert it into a
specific linked list.
• If there is any collision (i.e. two different elements have same hash
value) then store both the elements in the same linked list.
27. Applications
• Associative arrays: Hash tables are commonly used to implement many types
of in-memory tables. They are used to implement associative arrays (arrays
whose indices are arbitrary strings or other complicated objects).
• Database indexing: Hash tables may also be used as disk-based data structures
and database indices (such as in DBMS).
• Caches: Hash tables can be used to implement caches i.e. auxiliary data tables
that are used to speed up the access to data, which is primarily stored in slower
media.
• Object representation: Several dynamic languages, such as Perl, Python,
JavaScript, and Ruby use hash tables to implement objects.
• Hash Functions are used in various algorithms to make their computing faster.
28. Dictionaries
• In a dictionary, we separate the data into two parts.
• Each item stored in a dictionary is represented by a key/value pair.
• The key is used to access the item.
• With the key you can access the value, which typically has more information.
• Each key identifies one entry; that is, each key is unique.
• However, nothing prevents two different keys from referencing the same value.
• The contains test is in the dictionary replaced by a test to see if a given key is
legal.
• Finally, data is removed from a dictionary by specifying the key for the data
value to be deleted.
29. Operations on Dictionaries
Operation Function
put(key, value) Place the key and value association into the dictionary
get(key) Retrieve the value associated with the given key.
containsKey(key) Return true if key is found in dictionary
removeKey(key) Remove key from association
keys() Return iterator for keys in dictionary
size() Return number of elements in dictionary