Unit IV - Merge Sort
Unit IV - Merge Sort
1
The divide-and-conquer
approach
Recursive in structure
2
An Example: Merge Sort
Divide: Divide the n-element sequence to be
sorted into two subsequences of n/2
elements each
Conquer: Sort the two subsequences
recursively using merge sort.
Combine: Merge the two sorted
subsequences to produce the sorted answer.
3
Merge Sort
To sort n numbers
if n = 1 done!
recursively sort 2 lists of numbers n/2 and n/2 elements
merge 2 sorted lists in O(n) time
Strategy
break problem into similar (smaller) subproblems
recursively solve subproblems
combine solutions to answer
4
Merge Sort Procedure
The procedure MERGE-SORT(A, p, r) sorts the elements
in the sub-array A[ p…r].
The divide step simply computes an index q that partitions
A[ p…r] into two sub-arrays: A[ p…q], containing n/2
elements, and A[ q + 1…r], containing n/2 elements.
5
Merge Sort Procedure
To sort the entire sequence A ={A[1], A[2], . . . ,
A[ n]}, we make the initial call
MERGE-SORT( A, 1, length[ A]),
where length[ A] = n.
6
Merge
The key operation of the merge sort algorithm is the
merging of two sorted sequences in the "combine" step.
To perform the merging, we use an auxiliary procedure
MERGE(A, p, q, r), where A is an array and p, q, and r
are indices numbering elements of the array such that p ≤
q < r.
7
Merge algorithm
8
.Merge algorithm cont
9
.Merge algorithm cont
The operation of lines 10-17 in the call MERGE(A, 9, 12, 16)
10
Merge Sort
11
Merge Sort
12
.Merge Sort cont
15
.Analysis of Merge Sort cont
16
// Until we reach either end of either L or M, pick larger among
elements L and M and place them in the correct position at
// Merge sort in C A[p..r]
18