【发布时间】:2019-08-08 08:40:35
【问题描述】:
我的代码应该使用递归分治法返回给定数组中的最大数字。
对于 [1,3,2,4,6] 我应该返回 6。
由于某种原因,我的代码在第 47 行是 StackOverflowing
线程“主”java.lang.StackOverflowError 中的异常 在 maiordivisaoconquista.DivideAndConquer.Highest(DivideAndConquer.java:47)
public class DivideAndConquer {
/**
* @param args the command line arguments
*/
public static void main(String[] args)
{
Scanner s = new Scanner (System.in);
int n = s.nextInt();
int a[] = new int [n];
for(int i = 0; i < a.length; i++)
{
a[i] = s.nextInt();
}
int first = 0;
int last = a.length;
System.out.println(Highest(a,first,last));
}
public static int Highest (int a[], int first, int last)
{
if(first == last)
{
return a[first];
}
if (last - first == 1)
{
return Math.max(a[first],a[last]);
}
else
{
int middle = (first +last)/2;
return(Math.max(Highest(a,first,last),Highest(a,middle+1,last)));
}
}
}
【问题讨论】:
标签: java arrays recursion methods divide-and-conquer