通过递归分治法得到数组中的最高数
Highest number in a array by recursive divide and conquer
我的代码应该return使用递归分治法的给定数组中的最大数字。
对于[1,3,2,4,6]我应该return 6.
出于某种原因,我的代码在第 47 行中出现 Whosebuging
Exception in thread "main" java.lang.WhosebugError
at 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)));
}
}
}
改成这样:
return(Math.max(Highest(a, first, last), Highest(a, middle+1, last)));
|
|
V
return(Math.max(Highest(a, first, middle), Highest(a, middle+1, last)));
您的代码使用相同的 first
和 last
值调用自身,因此(通常)会无限递归。
我的代码应该return使用递归分治法的给定数组中的最大数字。
对于[1,3,2,4,6]我应该return 6.
出于某种原因,我的代码在第 47 行中出现 Whosebuging
Exception in thread "main" java.lang.WhosebugError at 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)));
}
}
}
改成这样:
return(Math.max(Highest(a, first, last), Highest(a, middle+1, last)));
|
|
V
return(Math.max(Highest(a, first, middle), Highest(a, middle+1, last)));
您的代码使用相同的 first
和 last
值调用自身,因此(通常)会无限递归。