Prelab: Hector Hash In this lab, we use arrays to implement hash

advertisement
Prelab: Hector Hash
In this lab, we use arrays to implement hash tables. The index of element is the key, while the
element stores data. Here is the hash function we will use in this lab:
h(x) = (3x+7) mod 17
If we have a hash table with initial size 17, and insert digit 1 into the hash table, we calculate the
key (index of element) using the hash function: h(1) = 10. Then we insert the digit 1 into index-10
spot as shown below
Collision solution
After we insert a list of numbers (1, 3, 7, 9, 11, 21) into the hash table, some spots are taken.
Now, we want to insert 24 into the hash table, and get the key h(24) = 11. However, the index-11
spot is already taken by 7, thus we have a collision.
In this lab, we have three collision solutions:
Linny
Searching for the next open spot after the current occupied spot.
In this case, index 12 is open, so we insert 24 there. If index 12 had been full, we would have
tried index 13, etc. In other words, h(x) = (3x + 7 + attempt) mod 17.
Doubles:
Using a second hash function to computer the jump amount based on the key.
h'(x) = 13 – (x mod 13)
Then use jump value in the new version of hash function:
h(x) = (3x + 7 + attempt * h'(x)) mod 17.
In the insert-24 example, the first attempt (attempt=0), we get h(24)0 = 11, and we get a collision.
In the second attempt (attempt=1), h'(24)=2, h(24)1=13, we find index-13 spot, which is open.
Cheney
Handle collisions by forcing the elements into a linked list. If the spot is NULL, it is open. If the
spot is a single element, it is occupied. If the spot contains a linked list, there are collisions.
Again in the previous insert-24 example, we insert 24 as shown below
Questions:
1. In the final “Linny” table above, insert x==15 into the hash table. How many attempts did
the insertion take?
2. In the final “Doubles” table above, insert x==15 into the hash table. How many attempts
did the insertion take?
3. In the final “Cheney” table above, insert x==15 into the hash table. How long was the
chain at the index where you inserted the value before you inserted it?
Download