查找最小Int的递归方法?

时间:2015-04-24 18:39:53

标签: java arrays recursion methods minimum

所以我有一个赋值,我必须创建一个接受int []参数并返回最小int的方法。但是只有一个问题......我们必须使用递归!无论如何,这是我的代码:

static int[] arr = {12, 8, 4, 17};

public static void main(String[] args){
System.out.println("Minimum is :" + findMin(arr));
}

public static int findMin(int[] iArray){
    if(arr.length == 0) {
        System.err.println("Please Pass An Array With At Least 1 Element.");
        return (Integer) null;
    }
    else return findMinFromArray(iArray, 0, iArray[0]); //call method with starting parameters ie index = 0 & min = iArray[0]
}

private static int findMinFromArray(int[] iArray, int index, int min) {
    if(index <= (iArray.length - 1)){
        if(iArray[index] < min){
            min = iArray[index];
        }
        System.out.println("Before: " + "Index = " + index + " | Min = " + min);
        findMinFromArray(iArray, index + 1, min);
    }
    System.out.println("After: " + "Index = " + index + " | Min = " + min);
    return min;
}

这是输出......

Before: Index = 0 | Min = 12
Before: Index = 1 | Min = 8
Before: Index = 2 | Min = 4
Before: Index = 3 | Min = 4
After: Index = 4 | Min = 4
After: Index = 3 | Min = 4
After: Index = 2 | Min = 4
After: Index = 1 | Min = 8
After: Index = 0 | Min = 12
Minimum is :12

正如你所看到的,代码是有效的,但我不知道如何让程序停止,而不是像它正在做的那样再回来。

3 个答案:

答案 0 :(得分:2)

你的错误是忽略了递归调用的结果。

更改

findMinFromArray(iArray, index + 1, min);

return findMinFromArray(iArray, index + 1, min);

完全固定的方法:

private static int findMinFromArray(int[] iArray, int index, int min) {
    if(index <= (iArray.length - 1)){
        if(iArray[index] < min){
            min = iArray[index];
        }
        System.out.println("Before: " + "Index = " + index + " | Min = " + min);
        return findMinFromArray(iArray, index + 1, min);
    }
    System.out.println("After: " + "Index = " + index + " | Min = " + min);
    return min;
}

输出:

Before: Index = 0 | Min = 12
Before: Index = 1 | Min = 8
Before: Index = 2 | Min = 4
Before: Index = 3 | Min = 4
After: Index = 4 | Min = 4

答案 1 :(得分:0)

Java是pass by value。这意味着如果更改方法内部参数的值,则此更改不会反映到调用方法时使用的变量。这适用于您的int min参数。

除此之外,您永远不会在内部使用findMinFromArray的结果来检查最小值:iArray[index]的当前值或此方法的结果。

我会重新设计方法findMinFromArray以省略变量int min并返回当前索引的最小值以及此方法的结果:

private static int findMinFromArray(int[] iArray, int index) {
    if(index <= (iArray.length - 1)) {
        int current = iArray[index];
        int otherMin = findMinFromArray(iArray, index + 1);
        return (current < otherMin) ? current : otherMin;
    }
    return Integer.MAX_VALUE;
}

与目前的问题无关,但这里还有另一个问题:

return (Integer) null;

当您将空数组作为参数发送时,这将抛出NullPointerException。而是返回类似Integer.MAX_VALUE的值。

答案 2 :(得分:0)

只是为了另一种可能的解决方案:

int minValue(int[] arr, int index) {
  if (index == arr.length - 1) return arr[index];
  else return Math.min(arr[index], minValue(arr, index + 1));
}

int[] arr = {12, 8, 4, 17};
System.out.println("Minimum is :" + minValue(arr, 0));

(此解决方案中未检查空数组