归并排序算法

2021-02-01 13:17

阅读:588

标签:rri   col   orm   string   void   static   stat   result   else   

public class NormalMergeSort {
    int[] arr;
    public NormalMergeSort(int[] arr){
        this.arr = arr;
    }
    public void MergeSort(){
        MergeSort(0,this.arr.length-1);
    }
    public void MergeSort(int left,int right){
        if(leftright){
            MergeSort(left,(left+right)/2);
            MergeSort((left+right)/2+1,right);
            Merge(left,(left+right)/2,(left+right)/2+1,right);
        }
    }
    public void Merge(int left,int leftEnd,int right,int rightEnd){
        final int originIndex = left;   //保留开头下标
        int[] tmpArr = new int[rightEnd-left+1];
        int tmpArrIndex = 0;
        while(leftrightEnd){
            if(this.arr[left]this.arr[right]){
                tmpArr[tmpArrIndex++] = this.arr[left++];
            }else{
                tmpArr[tmpArrIndex++] = this.arr[right++];
            }
        }
        while(leftleftEnd){
            tmpArr[tmpArrIndex++]=this.arr[left++];
        }
        while (right  rightEnd) {
            tmpArr[tmpArrIndex++] = this.arr[right++];
        }

        tmpArrIndex = 0;
        for(int Index = originIndex;Index){
            this.arr[Index] = tmpArr[tmpArrIndex];
        }
    }

    public static void main(String[] args) {
        NormalMergeSort instance = new NormalMergeSort(new int[]{4,2,6,2,5,3,6,8,3,4,7});
        instance.MergeSort();
        int[] result = instance.arr;    //断点测试
    }
}

 

归并排序算法

标签:rri   col   orm   string   void   static   stat   result   else   

原文地址:https://www.cnblogs.com/Jimmy-hacks/p/12813232.html


评论


亲,登录后才可以留言!