c - 执行算法递归求小数,速度很慢

标签 c algorithm recursion

您好,我有以下代码

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>

#define min(x, y)(x < y)?(x):(y)
#define SIZE 1000

int valormenor(int a[], int n)
{
    if(n == 1)
        return a[0];
    else
        return min(a[0], valormenor(a + 1, n - 1));
}

int main(void)
{
    int arr[SIZE] = {0}, i;
    srand (time (NULL));
    for(i = 0; i < SIZE; i++)
        arr[i] = rand() % SIZE;
    arr[5] = -1;
    printf("%d\n", valormenor(arr, SIZE));

    return 0;
}

重点是不明白,因为找最小数的时间太长了,我的理论是这个递归函数实现的不好,你说的是谁?

最佳答案

让我们在这里扩展 min 宏:

return min(a[0], valormenor(a + 1, n - 1));

变成了

return (a[0] < valormenor(a + 1, n - 1))?(a[0]):(valormenor(a + 1, n - 1));

如您所见,valormenor 被调用了两次。这两个递归调用进行了四次递归调用,这进行了八次递归调用,依此类推。这是一个经典的双重评估错误。

不要使用这样的宏。他们只是不值得头疼。

关于c - 执行算法递归求小数,速度很慢,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29760282/

相关文章:

arrays - 算法 - 动态规划

python - 递归调用函数

typescript - 如何在 Typescript 中定义递归字符串文字类型

javascript - 通过替换另一个对象中的属性名称来创建新对象

c++ - 使用 dOxygen 记录具有指定指针的 typedef 结构?

c - 修改函数返回的内存地址内容

c - 我在哪里可以找到有关在 C/linux 中为 USB 设备创建驱动程序的更多信息?

algorithm - 扫描线算法

python - 如何订购连接列表

c - 如何在 Arduino 代码中使用延迟?