Recursion
A method can call itself, this is recursion. Recursive implementations of methods are often used, because they lead to compact elegant code, which is easier to understand than a coresponding implementation that does not use recursion.
The recursive programming technic knows three important rules (of thumb):
- Base case: The recursion has a base case. Always the first statement is conditional and has a 'return'.
- SubProblem: Recursive calls adress a subproblem that is smaller to solve in some sense, such that it converges to the base case.
- No Overlapping: Recursive calls shall not handle subproblems that overlapp.
From view of performance non recursive solutions are faster, and usually need less memory. (e.g binary search)
But some tasks are such complex that only a recursive solution leads to a (more or less understandable) code.
Example of recursive binary search:
public static int binSearch(int[] a, int key) {
return binSearch0(a, key, 0, a.length - 1);
}
public static int binSearch0(int[] a, int key, int from, int to) {
if (from > to) return -1;
// looks strange but (from + to) / 2 can oveflow
// (java bug which was active more than 10 years)
int mid = from + (to - from) / 2;
if (key < a[mid])
return binSearch0(a, key, from, mid - 1);
else if (key < a[mid])
return binSearch0(a, key, mid + 1, to);
else return mid;
}
In that example you see all three rules (base, sub, non oberlap).
Not that recursive functions often have a start function, 'binSearch' in the example. Where 'binSearch0' is the recursive function.