Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 353
Kevin Avatar asked Apr 20 '15 23:04

Kevin


People also ask

Why do recursive functions result into slower execution?

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.

Are recursive algorithms slower?

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.

Why does recursion takes so long?

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.

Does recursion reduce execution time?

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.


1 Answers

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.

like image 178
user2357112 supports Monica Avatar answered Oct 19 '22 14:10

user2357112 supports Monica