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:
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. 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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.