Recursion
Algorithmic recursion solves a problem by solving smaller instances of the same problem and combining the answers. The call stack holds the unfinished work. A base case stops the descent.
Detailed Explanation
The fundamentals page is about the language feature. This page is about when the feature is the algorithm.
Divide and conquer splits the input, recurses on the parts, and merges. Mergesort splits in half, sorts each half, and merges in linear time: T(n) = 2T(n/2) + O(n), which is O(n log n). Binary search discards half and recurses once: T(n) = T(n/2) + O(1), which is O(log n). Quicksort partitions and recurses on both sides; the extra work is the partition, not a merge.
Tree and graph algorithms are recursive because the data is. DFS on a tree is "visit this node, then DFS the children." On a graph you add a visited mark so a cycle is not an infinite descent.
Dynamic programming is recursion plus memory. fib(n) = fib(n-1) + fib(n-2) is O(2^n) calls. The same recurrence with a table of already-computed n is O(n). The recursive formulation is still the specification; the table is the implementation.
C does not optimize tail calls portably, so a recursion that could be a loop should be a loop when the depth is n. Recursion earns its keep when the state is a tree position, a partition boundary, or a set of choices (backtracking). Then the stack is a natural explicit stack you would otherwise allocate.
Always name the argument that shrinks. If you cannot point at why the next call is smaller, you do not have a proof of termination. Bound the depth when the input is hostile. A crafted 10,000-deep JSON tree will take down a recursive parser that assumed documents were friendly.
Code Examples
#include <stdio.h>
/* Binary search as recursion. lo inclusive, hi exclusive. */
static int find(const int *a, int lo, int hi, int key)
{
if (lo >= hi) {
return -1;
}
int mid = lo + (hi - lo) / 2;
if (a[mid] == key) {
return mid;
}
if (a[mid] < key) {
return find(a, mid + 1, hi, key);
}
return find(a, lo, mid, key);
}
int main(void)
{
int a[] = { 1, 3, 5, 7, 9 };
printf("%d\n", find(a, 0, 5, 7)); /* prints: 3 */
return 0;
}#include <stdio.h>
static void hanoi(int n, char from, char to, char via)
{
if (n == 0) {
return;
}
hanoi(n - 1, from, via, to);
printf("%c -> %c\n", from, to);
hanoi(n - 1, via, to, from);
}
int main(void)
{
hanoi(2, 'A', 'C', 'B');
/* prints:
A -> B
A -> C
B -> C */
return 0;
}Common Gotchas
A recursive algorithm without a shrinking argument does not terminate
the stack grows until the process dies.
Overlapping subproblems without memoization explode
naive recursive Fibonacci is the teaching example and a production incident waiting for a larger `n`.
Tail recursion is still `O(n)` stack in portable C
rewrite the tail-recursive walk of a list as a loop.
The combine step can dominate
a divide-and-conquer that copies the whole array at every level is `O(n log n)` space as well as time.