码迷,mamicode.com
首页 > 其他好文 > 详细

Merge Sort

时间:2018-03-07 10:28:22      阅读:191      评论:0      收藏:0      [点我收藏+]

标签:ges   anr   ase   tee   div   you   while   sid   int   

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

标签:ges   anr   ase   tee   div   you   while   sid   int   

原文地址:https://www.cnblogs.com/xiaofenyaonuli/p/8520256.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!