Merge Sort
Idea
Merge Sort uses divide-and-conquer: split the array into halves, sort each, then merge them into an ordered array.
归并排序演示
84571362
当前归并区间: [0, 1]
Algorithm
- Recursively split into halves until single-element subarrays.
- Merge pairs of subarrays in order to form sorted sequences.
- Repeat merging until fully sorted.
Pseudo-code:
function mergeSort(A, left, right):
if left < right:
mid = (left + right) // 2
mergeSort(A, left, mid)
mergeSort(A, mid+1, right)
merge(A, left, mid, right)
function merge(A, left, mid, right):
create tmp
i = left, j = mid+1, k = 0
while i <= mid and j <= right:
if A[i] <= A[j]:
tmp[k++] = A[i++]
else:
tmp[k++] = A[j++]
copy remaining to tmp
copy tmp back to A[left..right]
Complexity
- Best/worst/avg:
- Space:
- Stability: stable
Exercises
Exercise 1
Run merge sort on ; show the first merge result.
参考答案
思路:分组后两两归并。
步骤:
- 初始分组:[8,4],[5,7],[1,3],[6,2]
- 第一次归并:[4,8],[5,7],[1,3],[2,6]
答案:如上,第一次归并后每组有序。
Exercise 2
What are merge sort’s time and space complexities?
参考答案
思路:复杂度与空间。
步骤:
- 时间复杂度
- 空间复杂度
答案:时间 ,空间 。