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.

Proposition 11.1: The merge-sort tree associated with an execution of<br />

merge-sort on a sequence of size n has height log n.<br />

We leave the justification of Proposition 11.1 as a simple exercise (R-11.3). We<br />

will use this proposition to analyze the runn<strong>in</strong>g time of the merge-sort algorithm.<br />

Hav<strong>in</strong>g given an overview of merge-sort <strong>and</strong> an illustration of how it works, let us<br />

consider each of the steps of this divide-<strong>and</strong>-conquer algorithm <strong>in</strong> more detail.<br />

The divide <strong>and</strong> recur steps of the merge-sort algorithm are simple; divid<strong>in</strong>g a<br />

sequence of size n <strong>in</strong>volves separat<strong>in</strong>g it at the element with <strong>in</strong>dex n/2, <strong>and</strong> the<br />

recursive calls simply <strong>in</strong>volve pass<strong>in</strong>g these smaller sequences as parameters. The<br />

difficult step is the conquer step, which merges two sorted sequences <strong>in</strong>to a s<strong>in</strong>gle<br />

sorted sequence. Thus, before we present our analysis of merge-sort, we need to<br />

say more about how this is done.<br />

11.1.2 Merg<strong>in</strong>g Arrays <strong>and</strong> Lists<br />

To merge two sorted sequences, it is helpful to know if they are implemented as<br />

arrays or lists. Thus, we give detailed pseudo-code describ<strong>in</strong>g how to merge two<br />

sorted sequences represented as arrays <strong>and</strong> as l<strong>in</strong>ked lists <strong>in</strong> this section.<br />

Merg<strong>in</strong>g Two Sorted Arrays<br />

683

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

Saved successfully!

Ooh no, something went wrong!