1. 程式人生 > >Merge Sort

Merge Sort

|| .com div hand ace print 分享 origin 9.png

 1 public class MergeSort {
 2 
 3     public static void sortIntegers(int[] array) {
 4         // write your code here
 5         if (array == null || array.length ==0 ) {
 6             return ;
 7         }
 8         //!!!write outside could save some space than writing inside the merge function
 9
int[] helper = new int[array.length] ; 10 mergeSort(array, helper, 0, array.length-1) ; 11 } 12 13 private static void mergeSort(int[] array, int[] helper, int left, int right) { 14 //exist recursion 15 if (left>=right) { 16 return; 17 } 18
int mid = left + (right-left)/2 ; 19 /* 20 * 註意這裏不用的原因 [0,1] start = 0 mid = 0(1/2 in java = 0) end = 1 21 * mergeSort(A, helper, start, mid-1 ) (0,-1) will exit in the mergeSort so its ok 22 * mergeSort(A, helper, mid, end, ), (0,1) will become the same as the input, input size not decrease, so timeout!
23 * */ 24 mergeSort(array, helper, left, mid ); 25 mergeSort(array, helper,mid +1, right); 26 merge(array, helper, left, mid, right); 27 } 28 //merge //這兩邊往中間夾的算法,都要考慮一邊先結 29 private static void merge(int[] array,int[] helper, int left, int mid, int right) { 30 /*note 31 1) here both the left and right are index! so use <= right 32 2) when it comes to merge, left part and right part already sorted in the array! 33 [ 1,3,5 ; 6,7,9] 34 * */ 35 //copy [1,3,5 ; 6,7,9] from array to helper to save ori. value, so later we could use original val. from it to overwrite array 36 for (int i = left; i <= right; i++) { 37 helper[i] = array[i] ; 38 } 39 // use left as the pointer for array, use leftIndex and rightIndex as two pointers for helper array 40 int leftIndex = left ; 41 int rightIndex = mid + 1 ; 42 while (leftIndex <=mid && rightIndex <= right){ 43 if (helper[leftIndex] <= helper[rightIndex]){ 44 array[left++] = helper[leftIndex++] ; 45 } else{ 46 array[left++] = helper[rightIndex++] ; 47 } 48 } 49 //two pointers related ques. always have to do checking for one side left situation 50 //[ 6,7,9 ; 1,3,5 ]: the array will be [1,3,5;1,3,5], use the helper which keep the original value to overwrite it 51 while(leftIndex<=mid){ 52 array[left++] = helper[leftIndex++] ; 53 } 54 //[ 1,3,5 ; 6,7,9] === in this case, there would be left on the right but no need handle at all, the array already [1,3,5;6,7,9] 55 56 } 57 58 public static void main(String[] args){ 59 int[] array = {6,7,9 , 1,3,5} ; 60 sortIntegers(array) ; 61 print(array); 62 63 } 64 public static void print(int[] arr){ 65 for (int i = 0; i < arr.length; i++) { 66 System.out.println(arr[i]); 67 } 68 } 69 }

技術分享圖片

Merge Sort