Study Atlas › Computer Science › Programming

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

factorial(5) = 5 × factorial(4) = … = 120.

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

  1. Define the base case
  2. Express the problem in terms of smaller subproblems
  3. Combine results
  4. Ensure progress toward the base case

Open the interactive page with diagrams →

People behind it

References

  1. H. Abelson, G. J. Sussman, Structure and Interpretation of Computer Programs, Ch. 1.2.

Textbooks

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