Merge Sort
description
Transcript of Merge Sort
Merge Sort
Merging
The key to Merge Sort is merging two sorted lists into one, such that if you have two lists X (x1x2…xm) and Y(y1y2…yn) the resulting list is Z(z1z2…zm+n)
Example:L1 = { 3 8 9 } L2 = { 1 5 7 }
merge(L1, L2) = { 1 3 5 7 8 9 }
Merging (cont.)
3 10 23 54 1 5 25 75X: Y:
Result:
Merging (cont.)
3 10 23 54 5 25 75
1
X: Y:
Result:
Merging (cont.)
10 23 54 5 25 75
1 3
X: Y:
Result:
Merging (cont.)
10 23 54 25 75
1 3 5
X: Y:
Result:
Merging (cont.)
23 54 25 75
1 3 5 10
X: Y:
Result:
Merging (cont.)
54 25 75
1 3 5 10 23
X: Y:
Result:
Merging (cont.)
54 75
1 3 5 10 23 25
X: Y:
Result:
Merging (cont.)
75
1 3 5 10 23 25 54
X: Y:
Result:
Merging (cont.)
1 3 5 10 23 25 54 75
X: Y:
Result:
MERGE (A, p, q, r ) 1. n1 ← q − p + 1
2. n2 ← r − q3. Create arrays L[1 . . n1 + 1] and R[1 . . n2 + 1]4. FOR i ← 1 TO n1
5. DO L[i] ← A[p + i − 1]6. FOR j ← 1 TO n2
7. DO R[j] ← A[q + j ]8. L[n1 + 1] ← ∞9. R[n2 + 1] ← ∞10. i ← 111. j ← 112. FOR k ← p TO r13. DO IF L[i ] ≤ R[ j]14. THEN A[k] ← L[i]15. i ← i + 116. ELSE A[k] ← R[j]17. j ← j + 1
Merge Sort Algorithm MERGE-SORT (A, p, r)
1. IF p < r // Check for base case2. THEN q = FLOOR[(p + r)/2] // Divide step3. MERGE-SORT (A, p, q) // Divide step 4. MERGE-SORT (A, q+1,r) // Divide step 5. MERGE (A, p, q,r) // Conquer step.
Merge Sort Example
99 6 86 15 58 35 86 4 0
Merge Sort Example
99 6 86 15 58 35 86 4 0
99 6 86 15 58 35 86 4 0
Merge Sort Example
99 6 86 15 58 35 86 4 0
99 6 86 15 58 35 86 4 0
86 1599 6 58 35 86 4 0
Merge Sort Example
99 6 86 15 58 35 86 4 0
99 6 86 15 58 35 86 4 0
86 1599 6 58 35 86 4 0
99 6 86 15 58 35 86 4 0
Merge Sort Example
99 6 86 15 58 35 86 4 0
99 6 86 15 58 35 86 4 0
86 1599 6 58 35 86 4 0
99 6 86 15 58 35 86 4 0
4 0
Merge Sort Example
99 6 86 15 58 35 86 0 4
4 0Merge
Merge Sort Example
15 866 99 35 58 0 4 86
99 6 86 15 58 35 86 0 4
Merge
Merge Sort Example
6 15 86 99 0 4 35 58 86
15 866 99 58 35 0 4 86
Merge
Merge Sort Example
0 4 6 15 35 58 86 86 99
6 15 86 99 0 4 35 58 86
Merge
Merge Sort Example
0 4 6 15 35 58 86 86 99
Merge Sort Analysis
The Double Memory Merge Sort runs O (N log N) for all cases, because of its Divide and Conquer approach.
T(N) = 2T(N/2) + N = O(N logN)
Finally…
There are other variants of Merge Sorts including k-way merge sorting, but the common variant is the Double Memory Merge Sort. Though the running time is O(N logN) and runs much faster than insertion sort and bubble sort, merge sort’s large memory demands makes it not very practical for main memory sorting.
Important things to remember for the Midterm:
• Best Case, Average Case, and Worst Case = O(N logN)
• Storage Requirement: Double that needed to hold the array to be sorted.