Вы находитесь на странице: 1из 7

Hash table

Collisions

One problem with hashing is that it is possible that two strings can hash
into the same
location. This is called a collision
. We can deal with collisions using many strategies,such as
linear probing (looking for the next available location i+1, i+2, etc. from
the hashed value i),
quadratic probing (same as linear probing, except we look for available
positions i+1 , i + 4, i + 9, etc from the hashed v alue i and separate
chaining, the process of creating a linked list of values if they hashed
into the same location.
Collision in Hash table

In chaining, we place all the elements that hash to the same slot into the same linked list, as Figure 11.3 shows.
Slot j contains a pointer to the head of the list of all stored elements that hash to j ; if there are no such
elements, slot j contains NIL.
Problem on hash function
● Consider a hash table of size m=100 and the hash function h(k) = floor(m(kA mod 1)) for A =
(√5 − 1)/2 = 0.618033. Compute the location to which the key k = 123456 is placed in hash
table.
● A. 77
● B. 82
● C. 88
● D. 89
● Explanation h(k) = ↳m(kA mod 1)↵,
● A=(√5 − 1)/2=0.618033.
● given K = 123456, m=100.
● h(k) = ↳100(123456 x 0.618033 mod 1)↵ = ↳100(76299.88204 mod 1)↵
● = ↳100 x 0.882048)↵
● = ↳88.2048 ↵
● =88
Problem on hash function
● A hash function f defined as f (key) = key mod 13, with linear probing is used to
insert keys 55, 58, 68, 91, 27, 145. What will be the location of 79.
Problem on hash function
A hash function f defined as f(key)=key mod 7,with linear probing,insert the keys
37,38,72,48,98,11,56, into a table indexed from 0 to 6,then 11 will be stored in the
location
A.3 B.4 C.5 D.6

f(37)=37 mod7 = 2 So,37 will be put in location 2.


f(38)= 3. So,38 will be in third location
f(72)= 2 (Collision)

This results in a collision. With linear probing as the collision resolving strategy, the
alternate location for 72 will be the location 4
● Continuing this way, the final configuration will be 98,56,37,38,72,11,48.
Problem on hash function
A hash table has space for 100 records. What is the probability of
collision before the table is 10% full?
a) 0.45 b)0.5 c)0.3 d)0.34(approximately)
Explanation :
● If there is only one record, then the probability of a collision will be
1/100. If 2, then 2/100 etc., If 9 then 9/100. So, the required
probability is, (1+2+3...9)/100 = 0.45.

Вам также может понравиться