归并排序算法

Posted jimmy-hacks

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了归并排序算法相关的知识,希望对你有一定的参考价值。

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;    //断点测试
    }
}

 

以上是关于归并排序算法的主要内容,如果未能解决你的问题,请参考以下文章

排序算法之归并排序

排序算法归并排序

Java 归并排序算法

Java 归并排序算法

PHP实现归并排序算法(代码实例)

重学数据结构和算法之归并排序快速排序