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.

A Nonrecursive Array-Based Implementation of Merge-<br />

Sort<br />

There is a nonrecursive version of array-based merge-sort, which runs <strong>in</strong> O(n log<br />

n) time. It is a bit faster than recursive list-based merge-sort <strong>in</strong> practice, as it<br />

avoids the extra overheads of recursive calls <strong>and</strong> node creation. The ma<strong>in</strong> idea is<br />

to perform merge-sort bottom-up, perform<strong>in</strong>g the merges level-by-level go<strong>in</strong>g up<br />

the merge-sort tree. Given an <strong>in</strong>put array of elements, we beg<strong>in</strong> by merg<strong>in</strong>g every<br />

odd-even pair of elements <strong>in</strong>to sorted runs of length two. We merge these runs<br />

<strong>in</strong>to runs of length four, merge these new runs <strong>in</strong>to runs of length eight, <strong>and</strong> so on,<br />

until the array is sorted. To keep the space usage reasonable, we deploy an output<br />

array that stores the merged runs (swapp<strong>in</strong>g <strong>in</strong>put <strong>and</strong> output arrays after each<br />

iteration). We give a <strong>Java</strong> implementation <strong>in</strong> Code Fragment 11.4, where we use<br />

the built-<strong>in</strong> method System.arraycopy to copy a range of cells between two<br />

arrays.<br />

Code Fragment 11.4: An implementation of the<br />

nonrecursive merge-sort algorithm.<br />

691

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

Saved successfully!

Ooh no, something went wrong!