麻烦的递归合并排序错误

时间:2016-10-19 10:20:26

标签: sorting merge

我是Java的新手,并尝试在Java中实现mergesort。但是,即使在多次运行程序之后

这是方法mergeSort

public static int[] mergeSort(int[] array) {
    int size = array.length;
    if (size < 2)
        return array;
    else {
        int mid = array.length / 2;
        int leftSide = mid;
        int rightSide = size - mid;
        int[] left = new int[leftSide];
        int[] right = new int[rightSide];
        for (int i = 0; i < mid; i++)
            left[i] = array[i];
        for (int i = mid; i < size; i++)
            right[i - mid] = array[i];
        left = mergeSort(left);
        right = mergeSort(right);
        return merge(left, right);
    }
}

这是方法合并

private static int[] merge(int[] left, int[] right) {
    int[] sum = new int[left.length + right.length];
    int i = 0, j = 0, k = 0;
    while (i < left.length && j < right.length) {
        if (left[i] < right[i]) {
            sum[k] = left[i];
            i++;
            k++;
        } else {
            sum[k] = right[j];
            j++;
            k++;
        }
    }
    while (i < left.length) {
        sum[k] = left[i];
        k++;
        i++;
    }
    while (j < right.length) {
        sum[k] = right[j];
        k++;
        j++;
    }
    return sum;
}

全部 我很累 请帮我找出来

1 个答案:

答案 0 :(得分:0)

我发现了错误

这里是

while (i < left.length && j < right.length) {
    if (left[i] < right[j) {
        sum[k] = left[i];
        i++;
        k++;
    } else {
        sum[k] = right[j];
        j++;
        k++;
    }
}