我在Java中编写了mergesort(recursive)的代码。我尝试在IntelliJ中调试它,但是它什么也没做
public class Main {
public static void main(String[] args) {
int[] ar = {20, 35, -15, 7, 55, 1, -22};
mergeSort(ar);
System.out.println(Arrays.toString(ar));
}
private static void mergeSort(int[] arra) {
int l=arra.length;
int mid = l/2;
int[] left= Arrays.copyOfRange(arra,0,mid);
int[] right= Arrays.copyOfRange(arra,mid,l);
mergeSort(left);
mergeSort(right);
merge(left,right,arra);
}
public static void merge(int[] ll,int[] rr,int[] array) {
int nl = ll.length;
int nr = rr.length;
int l=0;int r=0;int a=0;
while(l<=nl && r<= nr) {
array[a++]=ll[l]<=rr[r] ? ll[l++] : rr[r++];
}
if (l<nl) {
while (l <= nl)
array[a++] = ll[l++];
}
if (r<nr) {
while (r<=nr)
array[a++] = rr[r++];
}
}
问题似乎在第21行,即“ mergesort(left);”
代码上也没有红色下划线,仍然没有,仍然没有结果。
答案 0 :(得分:0)
mergeSort()中存在无限循环。在函数内部的代码周围放置一个if案例,如下所示:
private static void mergeSort(int[] arra) {
if (arra.length > 1) {
int l = arra.length;
int mid = l / 2;
int[] left = Arrays.copyOfRange(arra, 0, mid);
int[] right = Arrays.copyOfRange(arra, mid, l);
mergeSort(left);
mergeSort(right);
merge(left, right, arra);
}
}
还可以在功能merge()中将<=替换为<,并且在类似情况下使用<< / p>:
while (l < nl && r < nr) {
array[a++] = ll[l] <= rr[r] ? ll[l++] : rr[r++];
}
if (l < nl) {
while (l < nl)
array[a++] = ll[l++];
}
if (r < nr) {
while (r < nr)
array[a++] = rr[r++];
}