c 递归求数组最大值
编译无错误,但是也无输出#include<stdio.h>
int max(int *a,int,int);
int max(int a[], int left,int n)
{
if (n - left <= 1)
return a;
int b1,b2;
b1 = max(a,left,n/2);
b2 = max(a,n/2,n);
return (b1>b2)?b1:b2;
}
int main(void)
{
int len,left = 0;
int a[] = {2,3,43,12,4,5,3,5,3,23,76,3,23,43,23,23};
len = sizeof(a) / sizeof(a);
printf("the max number in a is: %d\n",max(a,left,len));
return 0;
} 本帖最后由 sunrise085 于 2020-4-10 11:26 编辑
你的递归调用时,左右边界写错了。
你的写法中b2进入了死循环,b1的右边界和b2的左边界应该是(n-left)/2+left。
这样才是当前区间的一半
#include<stdio.h>
int max(int *a,int,int);
int max(int a[], int left,int n)
{
if (n - left <= 1)
return a;
int b1,b2;
b1 = max(a,left,(n+left)/2);//max(a,left,n/2);
b2 = max(a,(n+left)/2,n);//max(a,n/2,n);
return (b1>b2)?b1:b2;
}
int main(void)
{
int len,left = 0;
int a[] = {2,3,43,12,4,5,3,5,3,23,76,3,23,43,23,23};
len = sizeof(a) / sizeof(a);
printf("the max number in a is: %d\n",max(a,left,len));
return 0;
} https://blog.csdn.net/sinat_39286218/article/details/78460225 int max(int *a,int,int);
int max(int a[], int left,int n)
{
int mid=(left+n)/2;
if (n ==left)
return a;
int b1,b2;
b1 = max(a,left,mid);
b2 = max(a,mid+1,n);
return (b1>b2)?b1:b2;
}
int test(){
int len,left = 0;
int a[] = {2,3,43,12,4,5,3,5,3,23,76,3,23,43,23,23};
len = sizeof(a) / sizeof(a);
printf("the max number in a is: %d\n",max(a,left,len));
return 0;
}
int main(void)
{
test();
system("pause");
//getchar();
return 0;
}
我觉得加一个中间变量,会更容易理解些 六小鸭 发表于 2020-4-10 11:43
https://blog.csdn.net/sinat_39286218/article/details/78460225
学富五车,厉害的
4goodworld 发表于 2020-4-10 12:20
我觉得加一个中间变量,会更容易理解些
system("pause");
很高级,都没看懂{:5_109:}
页:
[1]