简体   繁体   中英

Finding Max of an array using Recursion

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

    }
}

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.

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

    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM