Recursion
A function that solves a problem by calling itself on smaller instances, with a base case to stop.
Edited by Alex C, EduAlx · Sources cited below
Explanation
Each call uses a stack frame; deep recursion can overflow the stack. Divide-and-conquer algorithms (mergesort, quicksort, binary search) are naturally recursive. Tail recursion can be optimised into loops in some languages. The Tower of Hanoi needs 2ⁿ – 1 moves.
Example
Code
def hanoi(n, a='A', b='B', c='C'):
if n == 0: return
hanoi(n-1, a, c, b)
print(f'move disc {n} {a}->{c}')
hanoi(n-1, b, a, c)
hanoi(3) # 7 moves
How it works, step by step
- Define the base case
- Express the problem in terms of smaller subproblems
- Combine results
- Ensure progress toward the base case
Open the interactive page with diagrams →
People behind it
- John McCarthy (1927–2011), Artificial intelligence, USA: Coined 'artificial intelligence' (1955), created Lisp and time-sharing ideas. Turing Award 1971.
- Alonzo Church
- Édouard Lucas
References
- H. Abelson, G. J. Sussman, Structure and Interpretation of Computer Programs, Ch. 1.2.
Textbooks
- Structure and Interpretation of Computer Programs, Harold Abelson, Gerald Jay Sussman (MIT Press, 2nd ed. 1996). Classic on programming and abstraction.
- Introduction to Algorithms, Thomas H. Cormen, Charles E. Leiserson, Ronald L. Rivest, Clifford Stein (MIT Press, 4th ed. 2022). 'CLRS', the standard algorithms text.
Related topics
Python programming essentialsHeaps and priority queuesNumber systems and data representationGreedy algorithms and minimum spanning treesBlockchain and distributed ledgersString algorithms and pattern matchingQuantum computingAutomata and formal languagesSoftware engineering and version controlMemory hierarchy and caches