Skip to main content
ICT
Lesson A18 - Merge and MergeSort
 
Main Previous Next
Title Page >  
Summary >  
Lesson A1 >  
Lesson A2 >  
Lesson A3 >  
Lesson A4 >  
Lesson A5 >  
Lesson A6 >  
Lesson A7 >  
Lesson A8 >  
Lesson A9 >  
Lesson A10 >  
Lesson A11 >  
Lesson A12 >  
Lesson A13 >  
Lesson A14 >  
Lesson A15 >  
Lesson A16 >  
Lesson A17 >  
Lesson A18 >  
Lesson A19 >  
Lesson A20 >  
Lesson A21 >  
Lesson A22 >  
Lesson AB23 >  
Lesson AB24 >  
Lesson AB25 >  
Lesson AB26 >  
Lesson AB27 >  
Lesson AB28 >  
Lesson AB29 >  
Lesson AB30 >  
Lesson AB31 >  
Lesson AB32 >  
Lesson AB33 >  
Vocabulary >  
 

B. A Merge Algorithm page 4 of 9

  1. The mergeSort algorithm requires a merge algorithm that we will design first.

  2. The method header and the specifications of the merge method are given below. You may assume the ArrayList definitions from the sorting template program in Lesson 17 apply.

    /* Preconditions: Lists A and B are non-empty and in sorted nondecreasing order.
    Action: Lists A and B are merged into one ArrayList, C.
    Postcondition: List C contains all the values from
    Lists A and B, in nondecreasing order.
    */
    void merge (ArrayList <Integer> A, ArrayList <Integer> B, ArrayList <Integer> C)

  3. The merge method breaks down into four cases:

    1. ArrayList A is done, so pull a value from ArrayList B.

    2. ArrayList B is done, so pull a value from ArrayList A.

    3. Neither is done, and if A[i] < B[j] (where i & j are index markers in lists A and B) then pull from ArrayList A.

    4. Neither is done, and if B[j] <= A[i] then pull from ArrayList B.

  4. It is important to deal with the four cases in the order described above. For example, if you are done with ArrayList A (if i > A.length-1), you do not want to inspect any values past A[i].
  1. Example of method merge results:

    See Transparency A18.2, Merging Two Lists

    A: 2 6 11 15 21

    B: 4 5 9 13 17 25 29

    C: 2 4 5 6 9 11 13 15 17 21 25 29

 

Main Previous Next
Contact
 © ICT 2006, All Rights Reserved.