八大排序--归并排序

归并排序(Merge Sort)也是一种常用的排序方法,“归并”的含义是将两个或两个以上的有序子序列合并成一个新的有序子序列。如图10-11为两组有序子序列的归并,有序子序列{4,25,34,56,69,74}和{15,26,34,47,52},通过归并把它们合并成一个有序子序列{4,15,25,26,34,34,47,52,56,69,74}。


package ch02;

import util.ArrayUtil;

public class MergeSort {
    public static void main(String[] args) {
//      int[] array = new int[]{2,8,6,4,3,9,1};
//      int[] array = new int[]{58,46,72,95,84,25,37,58,63,12};
        int[] array = new int[]{45,34,67,95,78,12,26,45};

        mergeSort(array);
        ArrayUtil.display(array);
    }
    public static void mergeSort(int[] arr){
        int[] tmpArr = new int[arr.length];
        mergeSort(arr,tmpArr,0,arr.length-1);
    }
    public static void mergeSort(int[] arr,int[] tmpArr,int left,int right){
        if(left<right){
            int center = (left+right)/2;
            mergeSort(arr,tmpArr,left,center);
            mergeSort(arr,tmpArr,center+1,right);
            merge(arr,tmpArr,left,center,right);
        }
    }
    public static void merge(int[] arr,int[] tmpArr,int leftPos,int center,int rightEnd){
        int leftEnd = center;
        int rightPos = center+1;
        int tmpPos = leftPos;
        int nums = rightEnd - leftPos + 1;
        while(leftPos<=leftEnd&&rightPos<=rightEnd){
            if(arr[leftPos]<arr[rightPos]){
                tmpArr[tmpPos++] = arr[leftPos++];
            }else{
                tmpArr[tmpPos++] = arr[rightPos++];
            }
        }
        while(leftPos<=leftEnd){
            tmpArr[tmpPos++] = arr[leftPos++];
        }
        while(rightPos<=rightEnd){
            tmpArr[tmpPos++] = arr[rightPos++];
        }
        for(int i= 0;i<nums;i++,rightEnd--){
            arr[rightEnd] = tmpArr[rightEnd];
        }
    }


}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值