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?
Recursion has a large amount of overhead as compared to Iteration. It is usually much slower because all function calls must be stored in a stack to allow the return back to the caller functions.
Recursion is slower and it consumes more memory since it can fill up the stack. But there is a work-around called tail-call optimization which requires a little more complex code (since you need another parameter to the function to pass around) but is more efficient since it doesn't fill the stack.
If the question is why it's taking so long it's because it has to calculate each previous number. It takes a long time because this is approach, although simple, is arguably the least efficient approach (double recursion) to doing fibonacci sequence calculations.
Recursion adds clarity and (sometimes) reduces the time needed to write and debug code (but doesn't necessarily reduce space requirements or speed of execution). Reduces time complexity. Performs better in solving problems based on tree structures.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With