如何用递归找出数组中的最大值

lfssay 2010-04-28 07:47:02
如何用递归找出数组中的最大值
如:int[] a = {1,2,3,4,5,6,7,8,9,10};
如何用递归找出它的最大值?





...全文
974 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
waichhj 2010-08-22
  • 打赏
  • 举报
回复
为什么要把那么简单的事情复杂化呢?
用循环更简洁
public int jisuan(int[] arr)
{
int max=0;
for (int i=0;i<arr.length-1;i++)
{
max = arr[i]>arr[i+1] ? arr[i]:arr[i+1];
}
return max;
}
shine333 2010-04-29
  • 打赏
  • 举报
回复
看我1楼的回复,如果可以则“孺子可教也”,否则,“不可救药”
luozhangwen 2010-04-29
  • 打赏
  • 举报
回复
功力有限, 只能做到这一步, 不能直接在递归用存在返回值为什么?  占个bd继续问哈




public class Test {
private int max;
public static void main(String[] args) {
Test test = new Test();
int i = test.test(new int[]{-456,1,3,5,7,9,3});
System.out.println(i);
}
public int test(int[] arr){
test(arr, Integer.MIN_VALUE, 0);
return max;
}
private void test(int[] arr,int nextMax,int nextIndex){
max = arr[nextIndex] > nextMax ? arr[nextIndex]:nextMax;
nextIndex++;
if(nextIndex < arr.length){
test(arr, max, nextIndex);
}
}
}

luozhangwen 2010-04-29
  • 打赏
  • 举报
回复

public class Test {
private int max;
public static void main(String[] args) {
Test test = new Test();
test.test(new int[]{-456,1,3,5,7,9,3}, Integer.MIN_VALUE,0);
System.out.println(test.max);
}
public void test(int[] arr,int nextMax,int nextIndex){
max = arr[nextIndex] > nextMax ? arr[nextIndex]:nextMax;
nextIndex++;
if(nextIndex < arr.length){
test(arr, max, nextIndex);
}
}
}


谁帮忙改一下, 我想用void test(..) 这个方法返回值是最大的数 .

改好了给我留个言. 谢谢啦.
lfssay 2010-04-29
  • 打赏
  • 举报
回复
非常感谢!!!!
shine333 2010-04-28
  • 打赏
  • 举报
回复
  static int max(int[] array) {
return max(array, 0);
}
static int max(int[] array, int from) {
if (from == array.length - 1) {
return array[from];
}
return Math.max(array[from], max(array, from + 1));
}

50,499

社区成员

发帖
与我相关
我的任务
社区描述
Java相关技术讨论
javaspring bootspring cloud 技术论坛(原bbs)
社区管理员
  • Java相关社区
  • 小虚竹
  • 谙忆
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧