Grade 12 Computer Science · Recursion
The same idea, another language
What carries over unchanged, and what is added.
The same mistake: it runs there, here it will not compile
A recursive function that forgot a return on one of its paths runs quietly in Python, and blows up much later somewhere else. The very same function in Java does not compile at all. And why, in Java, is the whole array passed again and again, instead of cutting a smaller piece from it?
In grade nine you learned that recursion is a function solving a problem by solving a smaller version of it, and that it requires two parts: a base case and a step that shrinks. All of that is true word for word. What is added this year are two things the new language allows: tracing exactly what happens, and knowing what it costs.
static int total(int[] items, int from) {
if (from >= items.length) return 0; // the base returns
return items[from] + total(items, from + 1);
}
// total(new int[]{4, 7, 2}, 0) -> 13
// the base is reached when "from" runs past the endWhy there is an extra parameter
In Python it was convenient to cut the list and pass the rest. In this language cutting an array creates a new array at every call, and that is expensive. The accepted form is to pass the array as it is and add a parameter saying where to start — it is the one that grows at every call, and it is the one approaching the base. This is no compromise: this form is both faster and more explanatory, because one sees exactly what changes between call and call.
| The part | In the example |
|---|---|
| A base case | The position passed the end |
| A step that shrinks | The position grows by one |
| The joining | The current cell plus the total of the rest |
Example 1 — why the base must return
- The function declares it returns a number.
- A path with no return breaks the declaration.
- And the code does not compile.
Example 2 — why a parameter and not cutting
- Cutting creates a new array at every call.
- The parameter costs nothing.
- And one sees exactly what changes.