归并排序

Version 1

    /**
     * 归并排序
     */
    private static int[] mergeSort(int[] src, int start, int end) {
        if (start == end) {
            return new int[]{src[start]};
        }
        int mid = (start + end) / 2;
        int[] leftArray = mergeSort(src, start, mid);
        int[] rightArray = mergeSort(src, mid + 1, end);
        return merge(leftArray, rightArray);
    }

    /**
     * 归并
     */
    private static int[] merge(int[] leftArray, int[] rightArray) {
        int[] rst = new int[leftArray.length + rightArray.length];
        int leftIndex = 0;
        int rightIndex = 0;
        int rstIndex = 0;
        while (leftIndex < leftArray.length && rightIndex < rightArray.length) {
            int left = leftArray[leftIndex];
            int right = rightArray[rightIndex];
            if (left < right) {
                rst[rstIndex] = left;
                leftIndex++;
            } else {
                rst[rstIndex] = right;
                rightIndex++;
            }
            rstIndex++;
        }
        while (leftIndex < leftArray.length) {
            rst[rstIndex] = leftArray[leftIndex];
            rstIndex++;
            leftIndex++;
        }
        while (rightIndex < rightArray.length) {
            rst[rstIndex] = rightArray[rightIndex];
            rstIndex++;
            rightIndex++;
        }
        return rst;
    }

Version 2 更优

    private static void mergeSortRecursive(int[] arr, int[] result, int start, int end) {
        if (start >= end)
            return;
        int len = end - start;
        int mid = (len >> 1) + start;
        int start1 = start;
        int end1 = mid;
        int start2 = mid + 1;
        int end2 = end;
        mergeSortRecursive(arr, result, start1, end1);
        mergeSortRecursive(arr, result, start2, end2);
        int k = start;
        while (start1 <= end1 && start2 <= end2)
            result[k++] = arr[start1] <= arr[start2] ? arr[start1++] : arr[start2++];
        while (start1 <= end1)
            result[k++] = arr[start1++];
        while (start2 <= end2)
            result[k++] = arr[start2++];
        for (k = start; k <= end; k++)
            arr[k] = result[k];
    }

    private static void mergeSort(int[] arr) {
        int len = arr.length;
        int[] result = new int[len];
        mergeSortRecursive(arr, result, 0, len - 1);
    }


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值