Auborey
Auborey

Reputation: 91

Recursive function to find largest in Array

I have this so far, I just need it to start at any index value given by a parameter, how would I add this.

    public static int maxElement(int[] a, int i){
    if (i > 0) {
        return Math.max(a[i], maxElement(a, i-1));
    } 

   else {
        return a[0];
    }
}

Upvotes: 0

Views: 1616

Answers (5)

KM11
KM11

Reputation: 757

maxElement method:

public static int maxElement(int[] a, int i) throws IndexOutOfLenght{

    if (i > a.length-1 || i < 0)
        throw new IndexOutOfLenght();
    else{
        if (i == a.length-1)
            return a[i];
        else            
            return Math.max(a[i], maxElement(a, i+1));
    }
}

Main:

public static void main(String[] args) throws IndexOutOfLenght {
    int[] array = {1,2,3,4,5,6};
    System.out.println(maxElement(array,1));
}

Exception class:

public class IndexOutOfLenght extends Exception {
     IndexOutOfLenght() {
        super("IndexOutOfLenght ");
    }
}

Upvotes: 0

gerosalesc
gerosalesc

Reputation: 3063

public static int maxElement(int[] array, int index){
    //check all elements from index
    if (index >= 0 && index < array.length - 1) {
        return Math.max(array[index], maxElement(array, index+1));
    }
    // return last element
    return array[array.length -1];
}

Upvotes: 0

Yoda
Yoda

Reputation: 18068

public static int maxIndex(int i, int[] a){
   if(i == a.length - 1) return a.length - 1;
   int j = maxIndex(i+1, a);
   if(a[i] > a[j])
     return i;
   return j;
}

Use it by:

System.out.println(a[maxIndex(0, a)]);

Upvotes: 1

harshtuna
harshtuna

Reputation: 757

(not including code, as it is really trivial)

if you need to search for max element from index i to the end of array

1) use i as start index as @pbabcdefp instructed

2) in recursion check use array length, not zero

3) increment i in the recursion call

4) fall back to i-th element when reached end of array

that's it

Upvotes: 2

maraca
maraca

Reputation: 8743

public static int maxElement(int[] a, int i) {
  if (i < a.length - 1) {
    return Math.max(a[i], maxElement(a, i+1));
  } else {
    return a[a.length - 1];
  }
}

Go forward, adjust boundaries and you're done.

Upvotes: 1

Related Questions