Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angularjs/21.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Recursion 如果使用“为什么我会得到不同的输出?”;return";?_Recursion_Void - Fatal编程技术网

Recursion 如果使用“为什么我会得到不同的输出?”;return";?

Recursion 如果使用“为什么我会得到不同的输出?”;return";?,recursion,void,Recursion,Void,为什么在递归调用BubbleSort函数之前需要使用return语句 无返回语句:无输出 void BubbleSort(int arr[], int n, int j) { if(n == 1) return; if(j == n - 1) { BubbleSort(arr, n - 1, 0); } if(arr[j] > arr[j + 1]) { swap(arr[j], arr[j

为什么在递归调用BubbleSort函数之前需要使用return语句

无返回语句:无输出

void BubbleSort(int arr[], int n, int j)
{
    if(n == 1)
        return;

    if(j == n - 1)
    {
        BubbleSort(arr, n - 1, 0);
    }

    if(arr[j] > arr[j + 1])
    {
        swap(arr[j], arr[j + 1]);
    }

    BubbleSort(arr, n, j + 1);
    return;
}
with return语句:提供正确的输出

void BubbleSort(int arr[], int n, int j)
{
    if(n == 1)
        return;

    if(j == n - 1)
    {
        return BubbleSort(arr, n - 1, 0);
    }

    if(arr[j] > arr[j + 1])
    {
        swap(arr[j], arr[j + 1]);
    }

    BubbleSort(arr, n, j + 1);
    return;
}

通过指定
return
关键字,我们可以确保程序的控制将转移到调用程序

BubbleSort(arr, n - 1, 0);
当您执行此命令时,如果没有return关键字,它将调用self,而控件不会返回到它的调用者,因此其余的代码也将执行,它确实会更改原本不需要的业务,您可能会得到一些混乱的结果

以下代码片段可能有助于您更好地理解它:

if(j == n - 1)
{
    BubbleSort(arr, n - 1, 0);
    return; // returns to it caller.
}

如果不使用return,当最新的递归函数返回时,您将让程序继续执行,它将执行位于函数底部的
BubbleSort(arr,n,j+1)