Merge Sort

Posted xiaofenyaonuli

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Merge Sort相关的知识,希望对你有一定的参考价值。

Sort 的时间复杂度:o(n),  空间复杂度 o(logn)。

Merge 的时间复杂度: o(nlogn), 空间复杂度 o(n)。

总时间复杂度:o(nlogn)  总空间复杂度:o(n)。

 1 public class Solution {
 2   public int[] mergeSort(int[] array) {
 3     // Write your solution here
 4     if (array == null) {
 5       return array;//check null array first.
 6   }
 7     //allocate helper array to help merge sort.
 8     //so that we guanrantee no more than 0(n) space is used.
 9     //The space complexity is O(n) in this case.
10     int[] helper = new int[array.length];//把helper放前面,会节省运行的空间。
11     mergeSort(array, helper , 0, array.length - 1);
12     return array;
13   }
14   private void mergeSort(int[] array, int[] helper, int left, int right) {
15     if (left >= right) {
16       return;
17     }
18     int mid = left + (right - left)/2;//find the mid
19     mergeSort(array, helper, left, mid);
20     mergeSort(array, helper, mid+1, right);
21     merge(array, helper, left, mid, right);
22   }
23   private void merge(int[] array, int[] helper, int left, int mid, int right) {
24     //copy the content to helper array and we will merge from the 
25     //helper array.
26     for (int i = left; i <= right; i++) {
27       helper[i] = array[i];
28 }
29     int leftIndex = left;
30     int rightIndex = mid+1;
31     while (leftIndex <= mid && rightIndex <= right) {
32       if (helper[leftIndex] <= helper[rightIndex]) {
33         array[left++] = helper[leftIndex++];
34       } else {
35         array[left++] = helper[rightIndex++];
36       }
37           }
38      //if we still have some elements at left side, we need to copy them
39      while (leftIndex <= mid) {
40        array[left++] = helper[leftIndex++];
41        //if there are some elements at right side,we do not need to copy them
42        //because they are already in their position.
43        
44      }
45     
46 }
47   
48 }

 

以上是关于Merge Sort的主要内容,如果未能解决你的问题,请参考以下文章

归并排序(Merge Sort)思想,代码实现

自底向上归并排序(Merge Sort)

排序算法之归并排序(Merge Sort)

python [代码片段]一些有趣的代码#sort

归并排序(Merge sort)

归并排序(merge_sort)