c - 递归求数组最小值的方法

标签 c algorithm recursion

`/* finding the minimum number of a array */
#include<stdio.h>

int minimum(int n, int a[n], int x);

int main(void)
{

  int a[5] = { 5, 4, 3, 4, 5 };
  printf("%d \n", minimum(4, a, 0));
  return 0;
}

int minimum(int n, int a[n], int x)
{
  int minima;
  if (x >= n)
    return a[x];
  else
    minima = minimum(n, a, x + 1);
  if (a[x] > minima)
    return minima;
}
`

嘿,我在 stackoverflaw 中读到了一些递归源代码。使用JAVA也发现同样的问题。您能解释一下这段代码是如何工作的吗?或者这是一个很好的编码吗?我自己学习了递归,它正在工作。请解释一下。

最佳答案

您的代码中有两个问题:

  • 终止发生得太晚了:当 x==n 时返回 a[x] - 这是超出末尾的一个元素。
  • a[x] > minima 为 false 时,缺少返回:函数结束时不返回 a[x]

要解决这两个问题,请更改终止条件的检查,并添加缺少的返回:

if(x >= n-1) return a[n-1];
// You do not need an else after a return
minima = minimum(n,a,x+1);
if (a[x] > minima) return minima;
return a[x];

请注意,您可以通过从数组末尾开始搜索并向后搜索直到到达索引零来保存一个参数。

关于c - 递归求数组最小值的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18418680/

相关文章:

algorithm - 高效分布式计数

c - 对函数的每次递归调用是否使用相同的静态变量?

c - 我如何正确地在 C 中进行键捕获?

python - 为 Python C 扩展类型定义 __eq__

algorithm - 无向图可以有自环吗?

分而治之递归算法的复杂性

swift - 快速剖析排列算法

c - 在通过使用 16 位算术评估一个系列来计算 π 时避免溢出?

c - C 中的 free() 数据 block

c# - 当前日期公式中特定日期的最后日期