Merge Sort - 归并排序

核心:将两个有序对数组归并成一个更大的有序数组。通常做法为递归排序,并将两个不同的有序数组归并到第三个数组中。

先来看看动图,归并排序是一种典型的分治应用。

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))

原地归并

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. }

时间复杂度为 O(N \log N), 使用了等长的辅助数组,空间复杂度为 O(N)

Reference

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