通过递归划分和征服,数组中的最高数字

问题描述 投票:1回答:1

我的代码应该使用递归的分而治之方法返回给定数组中的最大数字。

对于[1,3,2,4,6],我应该返回6。

出于某种原因,我的代码是第47行的StackOverflowing

maiordivisaoconquista.DivideAndConquer.Highest(DivideAndConquer.java:47)中线程“main”java.lang.StackOverflowError中的异常

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
1个回答
1
投票

改变如下:

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)));

你的代码用相同的firstlast值调用自己,因此(通常)将无限递归。

© www.soinside.com 2019 - 2024. All rights reserved.