我已经用这个函数找到了最大元素 它适用于某些情况,但在其他情况下出现错误的位置,这就是我调用函数的情况。
int maxElement=maxi(names,noOfTeams,0,1,sum,0)
这是函数:
int maxi(string names[],int sizee,int prev,int next,int scores[],int maxx)
{
if (sizee ==1)return 0;
if (scores[maxx]<scores[next]) maxx=next;
if ((next+1)==sizee)return maxx;
else return maxi(names,sizee,prev+1,next+1,scores,maxx);
}
最佳答案
您的函数中有几个错误。
行
else if (scores[prev]<scores[next])maxx=next;
需要
else if (scores[maxx]<scores[next])maxx=next; // ^^^^
您在递归调用中缺少
return
。而不是else maxi(names,sizee,prev+1,next+1,scores,maxx);
应该是
else return maxi(names,sizee,prev+1,next+1,scores,maxx);
此外,还可以简化功能。
- 根本没有使用参数
name
。它可以被移除。 prev
参数也可以删除。- 您拥有的几张支票可以合二为一。
- 您不需要一系列
if-else-else
语句。
这是一个简化版本。
int maxi(int sizee, int next, int scores[], int maxx)
{
if ( sizee == next )
return maxx;
if (scores[maxx] < scores[next])
maxx=next;
return maxi(sizee, next+1, scores, maxx);
}
更重要的是,函数重载会更好:
int maxi(int sizee, int scores[]);
那应该是面向用户的功能。面向用户的函数的实现可以使用递归函数作为实现细节。
int maxi(int sizee, int scores[])
{
return maxi(sizee, 0, scores, 0);
}
在 http://ideone.com/chvtPA 查看它的工作情况.
关于c++ - 递归查找数组中最大值的位置c++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43664024/