Java学习总结--017归并排序

public class guibin {
    public static void main(String[] args) {
        int[] arr = {2, 10, 1, 0, 100, 3, 5, -1, 200, 109, 30, 1009, 109, 109, -100};
        //int[] arr={1,3,5,7,9,0,2,4,8,10};
        //归并排序
        chaiFen(arr, 0, arr.length - 1);
        System.out.println(Arrays.toString(arr));
    }
    private static void chaiFen(int[] arr, int startIndex, int endIndex) {
        //计算中间索引
        int centerIndex = (startIndex + endIndex) / 2;
        //递归来拆
        if (startIndex < endIndex) {
            //拆分左边
            chaiFen(arr, startIndex, centerIndex);
            //拆分右边
            chaiFen(arr, centerIndex + 1, endIndex);
            //归并
            mergerSort(arr, startIndex, centerIndex, endIndex);
        }
    }
    private static void mergerSort(int[] arr, int startIndex, int centerIndex, int endIndex) {
        //定义一个临时数组
        int[] tempArray = new int[endIndex - startIndex + 1];
        //定义临时数组的起始索引
        int index = 0;
        //定义左边数组的起始索引
        int i = startIndex;
        //定义右边数组的起始索引
        int j = centerIndex + 1;
        //循环比较左右两边数组的元素,往临时数组里面方法
        while (i <= centerIndex && j <= endIndex) {
            //进来比较
            if (arr[i] <= arr[j]) {
                tempArray[index] = arr[i];
                i++; //记得递增索引
            } else {
                tempArray[index] = arr[j];
                j++;//记得递增索引
            }
            index++; //临时数组的索引
        }
        //处理左边剩余元素
        while (i <= centerIndex) {
            tempArray[index] = arr[i];
            i++; //记得递增索引
            index++;
        }
        //处理右边剩余元素
        while (j <= endIndex) {
            tempArray[index] = arr[j];
            j++; //记得递增索引
            index++;
        }
        //这个时候我们的临时数组里面的元素已经排序好了
        //遍历临时数组,将临时数组中的元素,放到原数组里面去
        for (int k = 0; k < tempArray.length; k++) {
            arr[k + startIndex] = tempArray[k];
        }
    }
}

在这里插入图片描述

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/web116629/article/details/89740834