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.

idea is to iteratively remove the smallest element from the front of one of the two<br />

lists <strong>and</strong> add it to the end of the output sequence, S, until one of the two <strong>in</strong>put lists<br />

is empty, at which po<strong>in</strong>t we copy the rema<strong>in</strong>der of the other list to S. We show an<br />

example execution of this version of algorithm merge <strong>in</strong> Figure 11.6.<br />

Code Fragment 11.2: Algorithm merge for merg<strong>in</strong>g<br />

two sorted sequences implemented as l<strong>in</strong>ked lists.<br />

The Runn<strong>in</strong>g Time for Merg<strong>in</strong>g<br />

We analyze the runn<strong>in</strong>g time of the merge algorithm by mak<strong>in</strong>g some simple<br />

observations. Let n 1 <strong>and</strong> n 2 be the number of elements of S 1 <strong>and</strong> S 2 , respectively.<br />

Algorithm merge has three while loops. Independent of whether we are analyz<strong>in</strong>g<br />

the array-based version or the list-based version, the operations performed <strong>in</strong>side<br />

each loop take O(1) time each. The key observation is that dur<strong>in</strong>g each iteration of<br />

one of the loops, one element is copied or moved from either S1 or S 2 <strong>in</strong>to S (<strong>and</strong><br />

that element is considered no further). S<strong>in</strong>ce no <strong>in</strong>sertions are performed <strong>in</strong>to S 1<br />

or S 2 , this observation implies that the overall number of iterations of the three<br />

n 2 ).<br />

loops is n 1 +n 2 . Thus, the runn<strong>in</strong>g time of algorithm merge is 0(n 1 +<br />

Figure 11.6: Example of an execution of the<br />

algorithm merge shown <strong>in</strong> Code Fragment 11.2.<br />

685

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

Saved successfully!

Ooh no, something went wrong!