归并排序

2019-10-13  本文已影响0人  理想是一盏灯
public static void main(String[] args) {
    int arr[] ={9,8,7,4,6,3,5,0};
    System.out.println(Arrays.toString(MergeSort(arr,0,7)));
}

public static int[] MergeSort(int arr[] , int start ,int end){

    if(start>=end){
        return arr;
    }
    int mid=(start+end)/2;
    MergeSort(arr,start,mid);
    MergeSort(arr,mid+1,end);
    twoMerge(arr,start,mid,end);
    return arr;

}

public static int[] twoMerge(int arr[],int left,int mid,int right ){
    int[] temp =new int[right-left+1];
    int i=left;
    int j=mid+1;
    int index=0;
    while(i<=mid&&j<=right){
        if(arr[i]<arr[j]){
            temp[index]=arr[i];
            i++;
            index++;
        }else{
            temp[index]=arr[j];
            j++;
            index++;
        }
    }

    while(i<=mid){
        temp[index]=arr[i];
        i++;
        index++;
    }
    while(j<=right){
        temp[index]=arr[j];
        j++;
        index++;
    }

    int start=left;
    for(int k=0;k<temp.length;k++){
        arr[start+k]=temp[k];
    }
    return temp;
}
上一篇下一篇

猜你喜欢

热点阅读