归并排序

 

https://blog.csdn.net/qq_36442947/article/details/81612870

https://blog.csdn.net/MoreWindows/article/details/6678165 

重点先理解两个有序数组合并

基于上面blog的优化版

减少了数组的创建

public static void mergeArray(int[] a, int[] result, int left, int mid, int right) {
        int i = left;
        int m = mid;
        int j = mid + 1;
        int n = right;
        int k = left;
        while (i <= m && j <= n) {
            if (a[i] <= a[j]) {
                result[k++] = a[i++];
            } else {
                result[k++] = a[j++];
            }
        }
        while (i <= m) {
            result[k++] = a[i++];
        }
        while (j <= n) {
            result[k++] = a[j++];
        }
        for (int s = left; s <= right; s++) {
            a[s] = result[s];
        }
    }

    public static void mergeSort(int[] a, int[] result, int left, int right) {
        if (left < right) {
            int mid = (left + right) / 2;
            mergeSort(a, result, left, mid);
            mergeSort(a, result, mid + 1, right);
            mergeArray(a, result, left, mid, right);
        }
    }

 

posted @ 2020-06-10 21:25  java渣渣  阅读(135)  评论(0编辑  收藏  举报