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.

354<br />

Understanding Hash Tables<br />

A<br />

B<br />

C<br />

.<br />

Figure 3-7:<br />

Hash tables<br />

make<br />

searching<br />

faster by<br />

dividing<br />

data into<br />

distinct<br />

sections.<br />

V<br />

W<br />

X<br />

Y<br />

Hash Table<br />

Value<br />

Mail<br />

Versatile<br />

Plumbing<br />

Data<br />

When you store data with a unique key (a key-value pair), the key is used to<br />

help identify and retrieve the data. However, just using a key alone is no<br />

better than storing data alone because keys are just another chunk of data.<br />

The more data (and keys) you store, the longer it takes the computer to<br />

search through its entire list of keys.<br />

Converting keys with a hash function<br />

To speed up searching, dictionaries use hash tables. Basically, a hash table<br />

takes the keys used to identify data and then converts that key into a hash<br />

value. This hash value gets stored into a sorted list (table), as shown in<br />

Figure 3-8.<br />

The exact method used to convert a key into a value is a hash function. The<br />

converted key, or hash, now points directly to the stored data. At this point,<br />

the computer actually stores just two chunks of data:<br />

✦ The data itself<br />

✦ A hash value calculated from the key<br />

When you want to retrieve data, you give the computer the key associated<br />

with the data that you want. The computer takes the key and uses its hash<br />

function to convert the key to a value.

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

Saved successfully!

Ooh no, something went wrong!