码迷,mamicode.com
首页 > 编程语言 > 详细

归并排序算法

时间:2020-05-01 14:31:41      阅读:60      评论:0      收藏:0      [点我收藏+]

标签: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(left<right){
            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(left<=leftEnd&&right<=rightEnd){
            if(this.arr[left]<=this.arr[right]){
                tmpArr[tmpArrIndex++] = this.arr[left++];
            }else{
                tmpArr[tmpArrIndex++] = this.arr[right++];
            }
        }
        while(left<=leftEnd){
            tmpArr[tmpArrIndex++]=this.arr[left++];
        }
        while (right <= rightEnd) {
            tmpArr[tmpArrIndex++] = this.arr[right++];
        }

        tmpArrIndex = 0;
        for(int Index = originIndex;Index<=rightEnd;Index++,tmpArrIndex++){
            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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!