Merge Sort
Merge Sort
1
Divide and Conquer
Divide and Conquer
Divide-and-Conquer
1 2 3 4 5 6 7 8
7 2 9 4 3 8 6 1
⚫ To sort an array of n elements, we perform the following steps in
sequence:
⚫ If n < 2 then the array is already sorted.
⚫ Otherwise, n > 1, and we perform the following three steps in
sequence:
1. Sort the left half of the array using Merge Sort.
2. Sort the right half of the array using Merge Sort.
3. Merge the sorted left and right halves.
5
Merge Sort algorithm
l m h MergeSort(list, low, high)
0 1 2 3 4 5 6 7 {
7 2 9 4 3 8 6 1 if (low == high) return;
A1 A[p, q]
A[p, r]
A2 A[q+1, r]
7
Merge-Sort: Merge
Sorted
A:
merge
Sorted Sorted
FirstPart SecondPart
A:
A[left] 8
A[middle] A[right]
Merge-Sort: Merge Example
A: 2
5 3
5 7 28
15 8 30
1 4
6 5 14
10 6
L: R:
3 5 15 28 6 10 14 22
Temporary Arrays
Merge-Sort: Merge Example
A:
3
1 5 15 28 30 6 10 14
k=0
L: R:
3
2 15
3 28
7 30
8 6
1 10
4 14
5 22
6
i=0 j=0
Merge-Sort: Merge Example
A:
1 2
5 15 28 30 6 10 14
k=1
L: R:
3
2 5
3 15
7 28
8 6
1 10
4 14
5 22
6
i=0 j=1
Merge-Sort: Merge Example
A:
1 2 3 28 30
15 6 10 14
k=2
L: R:
2 3 7 8 6
1 10
4 14
5 22
6
i=1 j=1
Merge-Sort: Merge Example
A:
1 2 3 4 6 10 14
k=3
L: R:
2 3 7 8 6
1 10
4 14
5 22
6
i=2 j=1
Merge-Sort: Merge Example
A:
1 2 3 4 5 6 10 14
k=4
L: R:
2 3 7 8 6
1 10
4 14
5 22
6
i=2 j=2
Merge-Sort: Merge Example
A:
1 2 3 4 5 6 10 14
k=5
L: R:
2 3 7 8 6
1 10
4 14
5 22
6
i=2 j=3
Merge-Sort: Merge Example
A:
1 2 3 4 5 6 7 14
k=6
L: R:
2 3 7 8 6
1 10
4 14
5 22
6
i=2 j=4
Merge-Sort: Merge Example
A:
1 2 3 4 5 6 7 8
14
k=7
L: R:
3
2 5
3 15
7 28
8 6
1 10
4 14
5 22
6
i=3 j=4
Merge-Sort: Merge Example
A:
1 2 3 4 5 6 7 8
k=8
L: R:
3
2 5
3 15
7 28
8 6
1 10
4 14
5 22
6
i=4 j=4
Merge Algorithm(list, low, middle, high)
Merge Approach
{
int i, j, k; int result[ ];
i = low; j = middle+1; k = 0;
l m h while ((i <=middle) && (j <= high)) {
if(list[i] <= list[j]) {
0 1 2 3 4 5 6 7
result[k] = list[i]; k++; i++;
A 2 4 5 7 1 2 3 6 }
else {
result[k] = list[j]; k++; j++;
}
}
0 1 2 3 4 5 6 7 while(j<=h){
R result[k] = list[j]; k++; j++;
}
while(i<=m){
result[k] = list[i]; k++; i++;
}
for(k=0;k<=h;k++) {
list[k] = result[k]
}
}
Execution Example
7 2 9 43 8 6 1
20
Execution Example
7 29 4
21
Execution Example
7 29 4
72
22
Execution Example
7 29 4
72
7→7
23
Execution Example
7 29 4
72
7→7 2→2
24
Execution Example
⚫ Merge
7 2 9 43 8 6 1
7 29 4
72→2 7
7→7 2→2
25
Execution Example
7 29 4
72→2 7 9 4 → 4 9
26
Execution Example
⚫ Merge
7 2 9 43 8 6 1
7 29 4→ 2 4 7 9
72→2 7 9 4 → 4 9
27
Execution Example
7 29 4→ 2 4 7 9 3 8 6 1 → 1 3 6 8
72→2 7 9 4 → 4 9 3 8 → 3 8 6 1 → 1 6
28
Execution Example
⚫ Merge
7 2 9 43 8 6 1 → 1 2 3 4 6 7 8 9
7 29 4→ 2 4 7 9 3 8 6 1 → 1 3 6 8
72→2 7 9 4 → 4 9 3 8 → 3 8 6 1 → 1 6
29
Merge Sort – Time Complexity
MergeSort(list, low, high)
{
if (low == high) return;