繁体   English   中英

使用递归反转子数组的顺序

[英]Reversing the order of sub-array using Recursion

我试图严格使用递归来反转开始和结束索引之间的子数组顺序。 例如,如果子数组为1,2,3,4,它将变为4,3,2,1。

但是,我收到以下运行时错误:

java.lang.ArrayIndexOutOfBoundsException:-1

在finalExam.reverse(finalExam.java:13)

在finalExam.reverse(finalExam.java:17)

我不确定如何解决此问题。

谢谢。

 double[] reverse (double[] a, int start, int end) {
 if (start == end) {return a;}
 else {
 a[start] = a[end];
 a[end] = a[start];}


 return reverse (a, start+1, end-1);
}

(因为您提到考试结束了)。 这是您的代码存在的问题:

  • 您的支票应该start >= end
  • 您交换两个数字的代码不正确。

这是正确的解决方案:

public static double[] reverse (double[] a, int start, int end) {
    if (start >= end) {
        return a;
    }
    else {
        // this code will swap two elements
        double temp = a[start];
        a[start] = a[end];
        a[end] = temp;
    }
    return reverse (a, start+1, end-1);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM