Scarl - 2 months ago 17x

Java Question

For one of the questions i was asked to solve, I found the max value of an array using a for loop, so i tried to find it using recursion and this is what I came up with:

`public static int findMax(int[] a, int head, int last) {`

int max = 0;

if (head == last) {

return a[head];

} else if (a[head] < a[last]) {

return findMax(a, head + 1, last);

} else {

return a[head];

}

}

So it works fine and gets the max value, but my question is : is it ok to have for the base case return a[head] and for the case when the value at the head is > the value at last?

Answer

You could just as easily do it with only one counter, just the index of the value you want to compare this time:

```
public static int findMax(int[] a, int index) {
if (index > 0) {
return Math.max(a[index], findMax(a, index-1))
} else {
return a[0];
}
}
```

This much better shows what is going on, and uses the default "recursion" layout, e.g. with a common base step. Initial call is by doing `findMax(a, a.length-1)`

.

Source (Stackoverflow)

Comments