0

So it's pretty simple to find the max of an array using a for loop or a while loop, but I wanted to try it out with recursion. For some reason, the substring doesn't work - it says "cannot find symbol". Why is this? My strategy is continue subdividing and comparing the two sides until there is only one left which should be the max....am I doing it right? Thanks

   public static int max(int[] array) {

    if (array.length == 1) {
        return array[0];
    } else {
        int mid = (array.length) / 2;
        int leftmax = max(array.substring(0, mid));
        int rightmax = max(array.substring(mid, array.length));
        if (leftmax > rightmax) {
            return leftmax;
        } else {
            return rightmax;
        }

    }
}
7
  • what programming language is this? Java? JavaScript? Commented Mar 24, 2014 at 16:23
  • Why recursion? You might blow your stack. Commented Mar 24, 2014 at 16:26
  • I need to practice my recursion :o Commented Mar 24, 2014 at 16:28
  • If you wait few minutes, I will add answer with explained recursion which works. I hope you will learn from it, right now, you are not using recursion at all :). Commented Mar 24, 2014 at 16:30
  • 3
    @libik why do you say he is not using recursion? he is calling max() from within max(). That is recursion. Commented Mar 24, 2014 at 16:32

2 Answers 2

4

You are going to want to use Arrays.copyOfRange. Substring isn't going to work on an array.

int[] firstHalf = Arrays.copyOfRange(original, 0, original.length/2);
int[] secondHalf = Arrays.copyOfRange(original, original.length/2, original.length);

I can't comment on your algorithm.

Sign up to request clarification or add additional context in comments.

Comments

1

Since array is of type int[] not String, you cannot use substring(). Instead, keep track of which indexes you are searching through. Copying the array each iteration is a waste of both space and time.

int max( int[] array ){ return max( array, 0, array.length - 1 ); }

int max( int[] array, int low, int high )
{
    if (low == high) {
        return array[low];
    } 
    else {
        int mid = (high + low) / 2;
        int leftmax = max(array, low, mid );
        int rightmax = max(array, mid, high );
        if (leftmax > rightmax) {
            return leftmax;
        } 
        else {
            return rightmax;
        }

    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.