15.04.2018 Views

programming-for-dummies

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

358<br />

Understanding Hash Tables<br />

Avoiding collisions with double hashing<br />

Another way to avoid collisions is to use double hashing:<br />

1. The hash function calculates a hash value <strong>for</strong> each key.<br />

2. If a collision occurs, the computer calculates a second hash value.<br />

Essentially, you wind up with a hash table within another hash table, as<br />

shown in Figure 3-10.<br />

1<br />

2<br />

With double-hashing, the first hash table points to<br />

a second hash table, which points to the data.<br />

3<br />

4<br />

5<br />

1<br />

6<br />

2<br />

7<br />

3<br />

Figure 3-10:<br />

Double<br />

hashing<br />

creates<br />

miniature<br />

hash tables<br />

within a<br />

larger hash<br />

table.<br />

8<br />

Hash table #1<br />

Hash table #2<br />

4<br />

5<br />

6<br />

7<br />

8<br />

Dick<br />

Ross<br />

Sally<br />

Evans<br />

Double hashing can reduce the number of duplicate hash values (collisions),<br />

but here are a couple of drawbacks:<br />

✦ A collision can occur even after the double hashing.<br />

✦ Double hashing is a more complicated solution than chaining.<br />

The more complex a program, the greater the chances of something<br />

going wrong.

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!