Merge Sort - 合併排序

核心:將兩個有序對數組合併成一個更大的有序數組。通常做法為遞歸排序,並將兩個不同的有序數組合併到第三個數組中。

先來看看動圖,合併排序是一種典型的分治(divide and conquer)應用。

Merge Sort

Python

  1. #!/usr/bin/env python
  2. class Sort:
  3. def mergeSort(self, alist):
  4. if len(alist) <= 1:
  5. return alist
  6. mid = len(alist) / 2
  7. left = self.mergeSort(alist[:mid])
  8. print("left = " + str(left))
  9. right = self.mergeSort(alist[mid:])
  10. print("right = " + str(right))
  11. return self.mergeSortedArray(left, right)
  12. #@param A and B: sorted integer array A and B.
  13. #@return: A new sorted integer array
  14. def mergeSortedArray(self, A, B):
  15. sortedArray = []
  16. l = 0
  17. r = 0
  18. while l < len(A) and r < len(B):
  19. if A[l] < B[r]:
  20. sortedArray.append(A[l])
  21. l += 1
  22. else:
  23. sortedArray.append(B[r])
  24. r += 1
  25. sortedArray += A[l:]
  26. sortedArray += B[r:]
  27. return sortedArray
  28. unsortedArray = [6, 5, 3, 1, 8, 7, 2, 4]
  29. merge_sort = Sort()
  30. print(merge_sort.mergeSort(unsortedArray))

原地(in-place)合併

Java

  1. public class MergeSort {
  2. public static void main(String[] args) {
  3. int unsortedArray[] = new int[]{6, 5, 3, 1, 8, 7, 2, 4};
  4. mergeSort(unsortedArray);
  5. System.out.println("After sort: ");
  6. for (int item : unsortedArray) {
  7. System.out.print(item + " ");
  8. }
  9. }
  10. private static void merge(int[] array, int low, int mid, int high) {
  11. int[] helper = new int[array.length];
  12. // copy array to helper
  13. for (int k = low; k <= high; k++) {
  14. helper[k] = array[k];
  15. }
  16. // merge array[low...mid] and array[mid + 1...high]
  17. int i = low, j = mid + 1;
  18. for (int k = low; k <= high; k++) {
  19. // k means current location
  20. if (i > mid) {
  21. // no item in left part
  22. array[k] = helper[j];
  23. j++;
  24. } else if (j > high) {
  25. // no item in right part
  26. array[k] = helper[i];
  27. i++;
  28. } else if (helper[i] > helper[j]) {
  29. // get smaller item in the right side
  30. array[k] = helper[j];
  31. j++;
  32. } else {
  33. // get smaller item in the left side
  34. array[k] = helper[i];
  35. i++;
  36. }
  37. }
  38. }
  39. public static void sort(int[] array, int low, int high) {
  40. if (high <= low) return;
  41. int mid = low + (high - low) / 2;
  42. sort(array, low, mid);
  43. sort(array, mid + 1, high);
  44. merge(array, low, mid, high);
  45. for (int item : array) {
  46. System.out.print(item + " ");
  47. }
  48. System.out.println();
  49. }
  50. public static void mergeSort(int[] array) {
  51. sort(array, 0, array.length - 1);
  52. }
  53. }

C++

  1. void merge (vector<int>& arr, int low, int mid, int high){
  2. vector<int> helper(arr.size());
  3. for(int k = low; k <= high; k++){
  4. helper[k] = arr[k];
  5. }
  6. int i = low, j = mid+1;
  7. for(int k = low; k <= high; k++){
  8. if(i > mid){
  9. arr[k] = helper[j];
  10. j++;
  11. }
  12. else if(j > high){
  13. arr[k] = helper[i];
  14. i++;
  15. }
  16. else if(helper[j] > helper[i]){
  17. arr[k] = helper[j];
  18. j++;
  19. }
  20. else{
  21. arr[k] = helper[i];
  22. i++;
  23. }
  24. }
  25. }
  26. void mergeSort(vector<int>& arr, int low, int high){
  27. int mid = low + (high - low)/2;
  28. mergeSort(arr, low, mid);
  29. mergeSort(arr, mid + 1, high);
  30. merge(arr, low, mid, high);
  31. }

時間複雜度為 O(N \log N), 使用了等長的輔助陣列,空間複雜度為 O(N)

Reference

  • Mergesort - Robert Sedgewick 的大作,非常清晰。