我是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;
}
全部 我很累 请帮我找出来
答案 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++;
}
}