【发布时间】:2015-06-27 21:50:46
【问题描述】:
您好,我有以下代码
#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;
}
关键是不明白,因为找最小数的时间太长了,我的理论是这个递归函数实现得很糟糕,你声称吗?
【问题讨论】:
-
“非常慢”有多慢?但当然你是对的,因为所有不必要的开销,这是在数组中找到最小值的一种非常慢的方法与简单循环相比。
-
@romkyns 你能解释一下为什么这个函数效率低吗
-
你的算法是 O(n)²
-
@xsami 更像 O(2^n)
-
@Anonymous 谢谢我失败了:p