lundi 2 mars 2015

find maximum value recursively with a List


Vote count:

0




This method I'm trying to write finds the maximum value of integers in a list, and for the assignment I have to use recursion. I think I understand the concept of recursion, but doing it with Lists or arrays is something I don't understand. Does it always require splitting the List or array in half? Anyways, this code will compile, but I'm getting an IndexOutOfBounds error in a line I've commented below. Does it look remotely close to what I should be doing?



public static final int findMaxRecursively(List<Integer> numbers) {
int max = 0;

if(numbers.size() == 1)
return numbers.size();

List<Integer> bottomHalf = new ArrayList<Integer>(numbers.size()/2);
for (int i= 0; i<numbers.size()/2;i++){
if (bottomHalf.get(i) > max) // here's where the IndexOutOfBounds error occurs
max = bottomHalf.get(i);
}
findMaxRecursively(bottomHalf);

List<Integer> topHalf = new ArrayList<Integer>(numbers.size()/2);
for(int i = numbers.size()/2; i< numbers.size(); i++){
if (topHalf.get(i) > max)
max = topHalf.get(i);
}
findMaxRecursively(topHalf);

return max;
}


asked 20 secs ago







find maximum value recursively with a List

Aucun commentaire:

Enregistrer un commentaire