23.11.2014 Views

Data Structures and Algorithms in Java[1].pdf - Fulvio Frisone

Data Structures and Algorithms in Java[1].pdf - Fulvio Frisone

Data Structures and Algorithms in Java[1].pdf - Fulvio Frisone

SHOW MORE
SHOW LESS

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

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

an empty list-based map, we can easily use the separate cha<strong>in</strong><strong>in</strong>g rule to perform<br />

the fundamental map operations, as shown <strong>in</strong> Code Fragment 9.2.<br />

Code Fragment 9.2: The fundamental methods of<br />

the map ADT, implemented with a hash table that uses<br />

separate cha<strong>in</strong><strong>in</strong>g to resolve collisions among its n<br />

entries.<br />

For each fundamental map operation, <strong>in</strong>volv<strong>in</strong>g a key k, the separate-cha<strong>in</strong><strong>in</strong>g<br />

approach delegates the h<strong>and</strong>l<strong>in</strong>g of this operation to the m<strong>in</strong>iature list-based map<br />

stored at A [h(k)]. So, put(k, v) will scan this list look<strong>in</strong>g for an entry with key<br />

equal to k; if it f<strong>in</strong>ds one, it replaces its value with v, otherwise, it puts (k, v) at<br />

the end of this list. Likewise, get(k) will search through this list until it reaches<br />

the end or f<strong>in</strong>ds an entry with key equal to k. And remove(k) will perform a<br />

similar search but additionally remove an entry after it is found. We can "get<br />

away" with this simple list-based approach, because the spread<strong>in</strong>g properties of<br />

the hash function help keep each bucket's list small. Indeed, a good hash function<br />

will try to m<strong>in</strong>imize collisions as much as possible, which will imply that most of<br />

our buckets are either empty or store just a s<strong>in</strong>gle entry. This observation allows<br />

us to make a slight change to our implementation so that, if a bucket A[i] is<br />

empty, it stores null, <strong>and</strong> if A[i] stores just a s<strong>in</strong>gle entry (k,v), we can simply<br />

have A[i] po<strong>in</strong>t directly to the entry (k, v) rather than to a list-based map hold<strong>in</strong>g<br />

532

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

Saved successfully!

Ooh no, something went wrong!