Data Structures
Lecture: Merge Sort
By
Arvind Kumar
Asst. Professor
Lovely Professional University, Punjab
Divide and Conquer
• Recursive in structure
– Divide the problem into sub-problems that are
similar to the original but smaller in size
– Conquer the sub-problems by solving them
recursively. If they are small enough, just solve
them in a straightforward manner.
– Combine the solutions to create a solution to
the original problem
An Example: Merge Sort
Sorting Problem: Sort a sequence of n elements into
non-decreasing order.
• 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.
Blank
Merge Sort – Example
Original Sequence Sorted Sequence
18 26 32 6 43 15 9 1 1 6 9 15 18 26 32 43
18 26 32 6 43 15 9 1 6 18 26 32 1 9 15 43
43
18 26 32 6 43 15 9 1 18 26 6 32 15 43 1 9
18 26 32 6 43 15 9 1 18 26 32 6 43 15 9 1
18 26 32 6 43 15 9 1
Blank
Merge-Sort (A, p, r)
INPUT: a sequence of n numbers stored in array A
OUTPUT: an ordered sequence of n numbers
MergeSort (A, p, r) // sort A[p..r] by divide & conquer
1 if p < r
2 then q (p+r)/2
3 MergeSort (A, p, q)
4 MergeSort (A, q+1, r)
5 Merge (A, p, q, r) // merges A[p..q] with A[q+1..r]
Initial Call: MergeSort(A, 1, n)
Blank
Procedure Merge
Merge(A, p, q, r)
1 n1 q – p + 1
2 n2 r – q Input: Array containing
3 for i 1 to n1
4 do L[i] A[p + i – 1] sorted subarrays A[p..q]
5 for j 1 to n2 and A[q+1..r].
6 do R[j] A[q + j]
7 L[n1+1] Output: Merged sorted
8 R[n2+1] subarray in A[p..r].
9 i1
10 j1
11 for k p to r
12 do if L[i] R[j]
13 then A[k] L[i]
14 ii+1 Sentinels, to avoid having to
15 else A[k] R[j]
16 jj+1
check if either subarray is
fully copied at each step.
Blank
Questions?