Search code examples
javaarraysstack-overflowdivide-and-conquer

Java divide and conquer algorithm stack overflow error


I am trying to find out the index of the smallest number in an int array using divide and conquer and I have this stack overflow error:

Exception in thread "main" java.lang.StackOverflowError
    at java.lang.StrictMath.floor(Unknown Source)
    at java.lang.Math.floor(Unknown Source)

This is my divide and conquer method:

private static int dC(int[] a, int f, int l) {
        if(f == 1)
            return f;
        if(a[dC(a, f, (int)(Math.floor((double)(f+l)/2)))] > a[dC(a, (int)(Math.floor((double)(f+l)/2)+1), l)])
            return dC(a, (int)(Math.floor((double)(f+l)/2)+1), l);
        else
            return dC(a, f, (int)(Math.floor((double)(f+l)/2)));
    }

Here is what I put in my main method:

int[] a = {35,30,40,50};

System.out.println(dC(a, 0, 3));

Solution

  • You have a problem with your stoping "rule"

    private static int dC(int[] a, int f, int l) {
            if(l == f) // <-- This mean you have one item, so you want to return it.
                return f;
            if(a[dC(a, f, (int)(Math.floor((double)(f+l)/2)))] > a[dC(a, (int)(Math.floor((double)(f+l)/2)+1), l)])
                return dC(a, (int)(Math.floor((double)(f+l)/2)+1), l);
            else
                return dC(a, f, (int)(Math.floor((double)(f+l)/2)));
        }
    

    Also, I would try to do the calculation only once, so something like this (also what Joop Eggen said about Integers arithmetics):

    private static int dC(int[] a, int f, int l) {
            if(l == f)
                return f;
            int m = (f+l) / 2;
            int left = dC(a, f, m);
            int right = dC(a, m+1, l);
            if(a[left] > a[right])
                return left;
            else
                return right;
        }