简体   繁体   English

Java 递归 Function 不会返回值

[英]Java Recursive Function will not return a value

I am creating this binary search function that finds the correct point to return but never actually returns a value.我正在创建此二进制搜索 function,它找到了要返回的正确点,但实际上从未返回值。

''' '''

class Test {

static int binarySearch(int[] arr, int start, int end, int key) {
    int mid = (end - start) / 2 + start;
    while (end - start >= 1) {
        System.out.println(start + " " + mid + " " + end);
        if (arr[mid] == key) {
            System.out.println("returning " + mid);
            return mid;
        } else if (arr[mid] > key) {
            binarySearch(arr, start, mid, key);
        }else if (arr[mid] < key) {
            binarySearch(arr, mid, end, key);
        }
    }
    return -1;
}

public static void main(String[] args) {
    int[] arr = {1, 2, 3, 4, 5, 6};
    int x = binarySearch(arr, 0, arr.length, 6);
    System.out.println(x);

}

}

''' '''

Mid becomes 5 and it prints returning 5 but then skips the return statement and continues to loop. Mid 变为 5 并打印 returning 5 但随后跳过 return 语句并继续循环。 Why doesn't this just return 5?为什么这不只返回 5?

If you want to return a value from a nested call, you have to write code to do that.如果你想从嵌套调用中返回一个值,你必须编写代码来做到这一点。

You wrote:你写了:

 binarySearch(arr, start, mid, key);

which means (1) the return value from this is ignored, and (2) you will likely eventually fall through to the final 'return -1'.这意味着 (1) this 的返回值被忽略,并且 (2) 您可能最终会落入最终的“return -1”。 The.net effect is that the nested call is completely ineffective. .net效果是嵌套调用完全无效。

You presumably (I have not analyzed the code in detail) wanted:您大概(我没有详细分析代码)想要:

return binarySearch(arr, start, mid, key);

It occurs to me that perhaps you don't realize that 'return' only terminates the current execution of the method in which it is executed.我突然想到,也许您没有意识到“return”只会终止执行它的方法的当前执行。 It does not somehow unwind all of the nested calls and return from the outermost invocation.它不会以某种方式展开所有嵌套调用并从最外层调用返回。

So, 'return 5' returns 5 from the innermost level, and you're popped back into the loop at the next level out, and will carry on looping (and ignoring the 5).因此,“return 5”从最内层返回 5,然后您会跳回到下一层的循环中,并将继续循环(并忽略 5)。

But as a commenter observed, there's no need for the recursion with the loop, or else there's no need for the loop with the recursion.但正如一位评论者所观察到的,循环不需要递归,否则循环也不需要递归。

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

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