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.

11.4 Bucket-Sort <strong>and</strong> Radix-Sort<br />

In the previous section, we showed that Ω(nlogn) time is necessary, <strong>in</strong> the worst case,<br />

to sort an n-element sequence with a comparison-based sort<strong>in</strong>g algorithm. A natural<br />

question to ask, then, is whether there are other k<strong>in</strong>ds of sort<strong>in</strong>g algorithms that can<br />

be designed to run asymptotically faster than O(nlogn) time. Interest<strong>in</strong>gly, such<br />

algorithms exist, but they require special assumptions about the <strong>in</strong>put sequence to be<br />

sorted. Even so, such scenarios often arise <strong>in</strong> practice, so discuss<strong>in</strong>g them is<br />

worthwhile. In this section, we consider the problem of sort<strong>in</strong>g a sequence of entries,<br />

each a key-value pair.<br />

11.4.1 Bucket-Sort<br />

Consider a sequence S of n entries whose keys are <strong>in</strong>tegers <strong>in</strong> the range [0,N − 1],<br />

for some <strong>in</strong>teger N ≥ 2, <strong>and</strong> suppose that S should be sorted accord<strong>in</strong>g to the keys of<br />

the entries. In this case, it is possible to sort S <strong>in</strong> O(n + N) time. It might seem<br />

surpris<strong>in</strong>g, but this implies, for example, that if N is O(n), then we can sort S <strong>in</strong> O(n)<br />

time. Of course, the crucial po<strong>in</strong>t is that, because of the restrictive assumption about<br />

the format of the elements, we can avoid us<strong>in</strong>g comparisons.<br />

The ma<strong>in</strong> idea is to use an algorithm called bucket-sort, which is not based on<br />

comparisons, but on us<strong>in</strong>g keys as <strong>in</strong>dices <strong>in</strong>to a bucket array B that has cells<br />

<strong>in</strong>dexed from 0 to N − 1. An entry with key k is placed <strong>in</strong> the "bucket" B[k], which<br />

710

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

Saved successfully!

Ooh no, something went wrong!