Search code examples
javaarraysrecursionmethodsdivide-and-conquer

Highest number in a array by recursive divide and conquer


My code should return the highest number in a given array using a recursive divide and conquer method.

For a[1,3,2,4,6] i should return 6.

For some reason my code is StackOverflowing in the line 47

Exception in thread "main" java.lang.StackOverflowError 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)));
    }

 }
}

Solution

  • Change like this:

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

    Your code calls itself with the same first and last values, and so will (usually) infinitely recurse.