使用递归的数组的最小值.这是怎么回事

Minimum of an array using recursion. How does this work?

本文关键字:怎么回事 最小值 数组 递归      更新时间:2023-10-16

请有人解释一下下面的代码是如何工作的?

int minElement(int arr[], int n) {
if(n == 1)
return arr[0];
else {
int m = minElement(arr, n-1);
if(m < arr[n-1])
return m;
else
return arr[n-1];
}
}

我评论了每一行

int minElement(int arr[], int n) {
if(n == 1)  //When you reach the beginning of the array
return arr[0]; // Return the first element
else {
int m = minElement(arr, n-1); // See what the minimum spot is below n-1 index
if(m < arr[n-1]) // If the min element is below you return the min element
return m;
else
return arr[n-1]; // If not return your value as the min element up until the index
} // Repeat till you reach the top again
}

希望这能帮助