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 }