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

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

11.1.4 <strong>Java</strong> Implementations of Merge-Sort<br />

In this section, we present two <strong>Java</strong> implementations of the merge-sort algorithm,<br />

one for lists <strong>and</strong> the other for arrays.<br />

A Recursive List-Based Implementation of Merge-Sort<br />

In Code Fragment 11.3, we show a complete <strong>Java</strong> implementation of the listbased<br />

merge-sort algorithm as a static recursive method, mergeSort. A<br />

comparator (see Section 8.1.2) is used to decide the relative order of two<br />

elements.<br />

In this implementation, the <strong>in</strong>put is a list, L, <strong>and</strong> auxiliary lists, L1 <strong>and</strong> L2, are<br />

processed by the recursive calls. Each list is modified by <strong>in</strong>sertions <strong>and</strong> deletions<br />

only at the head <strong>and</strong> tail; hence, each list update takes O(1) time, assum<strong>in</strong>g the<br />

lists are implemented with doubly l<strong>in</strong>ked lists (see Table 6.4). In our code, we use<br />

class NodeList (Code Fragments 6.9–6.11) for the auxiliary lists. Thus, for a<br />

list L of size n, method mergeSort(L,c) runs <strong>in</strong> time O(nlogn) provided the list<br />

L is implemented with a doubly l<strong>in</strong>ked list <strong>and</strong> the comparator c can compare two<br />

elements of L <strong>in</strong> O(1) time.<br />

688

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

Saved successfully!

Ooh no, something went wrong!