mergesort

class Solution {
    public int[] mergeSort(int[] arr){
        if(arr.length<2||arr == null)
            return arr;   
        return MSort(arr,0,arr.length-1);
    }

    public int[] MSort(int[] arr, int low, int high){
            if(low < high){
                    int mid = (low+high)/2;
                    int[] left = MSort(arr,low,mid);
                    int[] right = MSort(arr,mid+1,high);
                    return mergeTwoList(left,right);
              }  
              return new int[]{arr[low]};
    }

    public int[] mergeTwoList(int[] A, int[] B) {
        int[] C = new int[A.length + B.length];
        int k = 0;
        int i = 0;
        int j = 0;
        while(i < A.length && j < B.length) {
            if (A[i] < B[j])
                C[k++] = A[i++];
            else
                C[k++] = B[j++];
        }
        while (i < A.length) 
            C[k++] = A[i++];
        while (j < B.length) 
            C[k++] = B[j++];
        return C;
    }
}

 

posted @ 2019-03-01 15:54  yanhowever  阅读(189)  评论(0编辑  收藏  举报