【问题标题】:Using recursion to find the smallest int an array?使用递归找到最小的 int 数组?
【发布时间】:2016-03-21 19:27:25
【问题描述】:

这是我的代码。

public static void main(String[] args) {


    int[] array = {5,3,1,0,4,7};
    int smallest = array[0];
    System.out.println(smallest(array,smallest));



}


private static int smallest(int[] array, int smallest){

    int count = 0;
    if(array[count] < smallest){
        smallest = array[count];
    }
    else if(array[count] == array[array.length-1]){
        return smallest;
    }
    count++;
    return smallest(array,smallest);

}

}

我需要使用 java 来使用 RECURSION 找到数组中的最小 int,我知道如何使用迭代来找到它,但这是严格的递归。任何帮助都会得到帮助。在我看来,这一行的错误在这里。

--> 返回最小(数组,最小);

【问题讨论】:

    标签: arrays recursion


    【解决方案1】:

    问题是每次调用“smallest”时都会创建一个版本的变量“count”,并为其分配0,因此在再次调用“smallest”之前增加它的值并不重要。 在函数内部创建的变量不会在函数调用之间共享。

    您遇到的问题是因为“count”始终为0并且递归永远不会结束,所以它以堆栈溢出错误结束。

    要解决这个问题,您必须添加另一个参数“count”,它将保存算法的迭代。

    public static void main(String[] args) {
    
    
    int[] array = {5,3,1,0,4,7};
    int smallest = array[0];
    System.out.println(smallest(array,smallest,0));
    
    
    
    }
    
    
    private static int smallest(int[] array, int smallest, int count){
    
    if(array[count] < smallest){
        smallest = array[count];
    }
    else if(array[count] == array[array.length-1]){
        return smallest;
    }
    
    return smallest(array,smallest,count+1);
    
    }
    

    【讨论】:

    • 天哪,在阅读您的评论之前,我确实做了同样的更改。我添加了 count 变量,它起作用了,但我很好奇是否可以不使用 count 变量?
    • 可以使用在 main() 和 minimum() 方法之外定义的全局静态“count”变量来实现...但我不建议使用全局变量。有一种不使用计数变量的方法,这意味着在每次最小()递归调用之前删除“数组”数组的第一个元素,......但是使用“计数”变量更容易和更快。跨度>
    【解决方案2】:

    除非您的代码进入ifelse if 块,否则它将继续前进并再次调用最小。由于您传递了完全相同的参数,因此您将获得完全相同的结果。 记住 count 是一个局部变量。

    另外,我认为您可能需要if 而不是else if,因为如果最后一个数字较小,您可能会遇到异常。

    【讨论】:

      【解决方案3】:

      当您有两个数字时,您只需比较它们以找到最小的。因此,如果您将数组一分为二,在每一半中找到一个最小的,然后只需比较结果即可找到最小的。这是您的递归大纲(注意:我没有编译或测试它):

      int getSmallest(ArrayList<Integer> numbers) { if (numbers.size() == 1) return numbers.get(0); int leftMin = getSmallest(numbers.subList(0, numbers.size()/2); int rightMin = getSmallest(numbers.subList(numbers.size()/2, numbers.size()); return leftMin < rightMin ? leftMin : rightMin; }

      如果你需要使用 int[],你仍然可以使用相同的方法,只是需要一些调整:)

      【讨论】:

        猜你喜欢
        • 2011-08-01
        • 2016-03-27
        • 2010-12-16
        • 2015-09-03
        • 2020-07-03
        • 1970-01-01
        • 2021-12-23
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多