简体   繁体   English

执行算法递归地寻找较低的数字,非常慢

[英]Execution algorithm recursively seeking lower number, is very slow

Hi I have the following code 嗨,我有以下代码

#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;
}

The point is that do not understand because it takes too long to find the smallest number, my theory is that this recursive function is badly implemented, you who claim to? 关键是不理解,因为找到最小的数会花费太长时间,我的理论是,此递归函数执行不正确,您声称谁呢?

Let's expand the min macro here: 让我们在这里展开min宏:

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

That becomes 那变成

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

As you can see, valormenor is called twice. 如您所见, valormenor被调用两次。 Those two recursive calls make four recursive calls, which make eight recursive calls, and so on. 那两个递归调用进行四个递归调用,再进行八个递归调用,依此类推。 It's a classic double evaluation bug. 这是经典的双重评估错误。

Don't use macros like this. 不要使用这样的宏。 They're just not worth the headaches. 他们只是不值得头疼。

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

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