A recursive method on an array usually needs extra parameters (an index, or a range) that the caller should not have to supply. The solution is a pair: a public method with the natural signature, and a private recursive helper that carries the extra parameters.
Write ArrayRecursion with these pairs — no loops in any of them:
| public | helper |
|---|---|
max(int[] a) |
max(a, high) — largest of a[0..high] |
sum(int[] a) |
sum(a, from) |
isSorted(int[] a) |
isSorted(a, i) |
isPalindrome(int[] a) |
isPalindrome(a, low, high) |
binarySearch(int[] a, int key) |
binarySearch(a, key, low, high) |
indexOf(int[] a, int key) |
indexOf(a, key, from) |
reverse(int[] a) |
reverse(a, low, high) — in place |
main reads n, the n values and a key. It uses the binary search when the array is sorted and the linear search otherwise. For the input
7
3 8 15 15 23 42 57
23
the program prints
Largest: 57
Sum: 163
Sorted: true
Palindrome: false
Binary search for 23: index 4
Reversed in place: 57 42 23 15 15 8 3