J.E.D.I.
6.3.2 An Example
Given
Maricar Vanessa
Margaux Hannah
Rowena
1
st
Pass
Hannah Vanessa
Margaux Maricar
Rowena
2
nd
Pass
Hannah Margaux
Vanessa Maricar
Rowena
3
rd
Pass
Hannah Margaux
Maricar Vanessa
Rowena
4
th
Pass
Hannah Margaux
Maricar Rowena
Vanessa
Figure 6.2: Selection sort example
6.4 Merge Sort
Before examining the Merge sort algorithm, let us first have a quick look at the divide- and-conquer paradigm since Merge sort closely follows this approach.
6.4.1 Divide-and-Conquer Paradigm
Several algorithms use recursion to solve a given problem. The original problem is split into subproblems, then the solutions to the subproblems lead to the solution of the main
problem. This type of algorithms typically follows the divide-and-conquer paradigm. At each level of recursion, the paradigm consists of three steps.
1. Divide Divide the main problem into subproblems.
2. Conquer Conquer the subproblems by recursively solving them. In the case that the
suproblems are simple and small enough, a straightforward manner of solving them would be better.
3. Combine Combine the solutions to the suproblems, which would lead to the solution of the
main problem.
6.4.2 Understanding Merge Sort
As previously mentioned, Merge sort uses the divide-and-conquer technique. Thus, the description of its algorithm is patterned after the three steps in the divide-and-conquer
paradigm. Here is how Merge sort works.
1. Divide Divide the sequence of data elements into two halves.
2. Conquer Conquer each half by recursively calling the Merge sort procedure.
3. Combine Combine or merge the two halves recursively to come up with the sorted sequence.
Recursion stops when the base case is reached. This is the case wherein the half to be
Introduction to Programming II Page 82
J.E.D.I.
sorted has exactly one element. Since only one element is left to be sorted, this half is already arranged in its proper sequence.
6.4.3 The Algorithm
void mergeSortObject array[], int startIdx, int endIdx { if array.length = 1 {
Divide the array into two halves, leftArr and rightArr mergeSortleftArr, startIdx, midIdx;
mergeSortrightArr, midIdx+1, endIdx; combineleftArr, rightArr;
} }
6.4.4 An Example
Given:
7 2 5 6
Divide given array into two: LeftArr RightArr
Introduction to Programming II Page 83
2 7 2
7 6
5 6 5
J.E.D.I.
Divide LeftArr of given into two: LeftArr RightArr
Introduction to Programming II Page 84
7 7
2 2
J.E.D.I.
Combine
2 7
Divide RightArr of given into two: LeftArr RightArr
Introduction to Programming II Page 85
5 5
6 6
J.E.D.I.
Combine
5 6
Combine LeftArr and RightArr of the given.
2 5 6 7
Figure 6.3: Merge sort example
6.5 Quicksort