The short answer
A recursive algorithm solves a problem by calling itself on a smaller version of the same problem. Each call does a little work and passes the rest along, until it reaches a case simple enough to answer directly. That simplest case is the base case. The answers then combine as the calls return.
Most recursive algorithms follow the same three steps:
- Check whether the input is a base case. If it is, return an answer.
- Otherwise, call the same function on one or more smaller inputs.
- Combine those results into the answer for the current call.
The examples below use Python. The same ideas apply in most programming languages.
Factorial: the simplest example
The factorial of a whole number n, written n!, is the product of all whole numbers from 1 to n. It has a natural recursive definition: n! equals n times (n - 1)!, and the factorial of 1 is 1.
def factorial(n):
if n <= 1: # base case
return 1
return n * factorial(n - 1) # recursive case
print(factorial(5)) # 120
The base case also covers 0, because 0! is defined as 1. Each call reduces n by one, so for any non-negative whole number the chain of calls reaches the base case.
Binary search
Binary search finds a value in a sorted list by checking the middle item. If the middle item is the target, it stops. If the target is larger, it searches the right half; if smaller, the left half. The recursive version makes that same choice by calling itself on the half that could contain the target.
def binary_search(items, target, low, high):
if low > high: # base case: range is empty
return -1
middle = (low + high) // 2
if items[middle] == target:
return middle
if items[middle] < target:
return binary_search(items, target, middle + 1, high)
return binary_search(items, target, low, middle - 1)
numbers = [2, 5, 8, 12, 16, 23, 38]
print(binary_search(numbers, 23, 0, len(numbers) - 1)) # 5
If the target is not in the list, the function returns -1. Because the range is cut in half each time, a list of 1,000 items needs at most about 10 comparisons. The running time grows as O(log n).
Tree traversal
Trees are naturally recursive. Each node has child subtrees, and each subtree is itself a tree. An in-order traversal visits the left subtree, then the node, then the right subtree. The base case is an empty subtree.
class Node:
def __init__(self, value, left=None, right=None):
self.value = value
self.left = left
self.right = right
def inorder(node):
if node is None: # base case: empty subtree
return []
return inorder(node.left) + [node.value] + inorder(node.right)
tree = Node(4, Node(2, Node(1), Node(3)), Node(6, Node(5), Node(7)))
print(inorder(tree)) # [1, 2, 3, 4, 5, 6, 7]
In a binary search tree, an in-order traversal lists the values in sorted order. Self-balancing trees, such as those described in avl tree in data structure, also often use recursion for insertion in textbook versions.
Tower of Hanoi
The Tower of Hanoi puzzle has three pegs and a stack of disks, all different sizes, on the first peg. You move one disk at a time, and you may never place a larger disk on a smaller one. The goal is to move every disk to the third peg.
The recursive idea is to move the top n - 1 disks out of the way, move the largest disk to the target peg, then move the n - 1 disks back on top of it.
def hanoi(n, source, target, spare, moves):
if n == 0: # base case: nothing to move
return
hanoi(n - 1, source, spare, target, moves)
moves.append((source, target))
hanoi(n - 1, spare, target, source, moves)
moves = []
hanoi(3, "A", "C", "B", moves)
print(len(moves)) # 7
The fewest moves for n disks is 2^n - 1, so three disks take 7 moves and ten disks take 1,023.
Fibonacci and the cost of naive recursion
Fibonacci numbers start with 0 and 1, and each later number is the sum of the two before it. The direct recursive version is short but wasteful.
def fib(n):
if n < 2: # base cases: fib(0) is 0, fib(1) is 1
return n
return fib(n - 1) + fib(n - 2)
This function recalculates the same smaller values over and over. Computing fib(30) this way makes more than a million function calls. Memoization fixes the problem by storing each result the first time it is computed:
from functools import lru_cache
@lru_cache(maxsize=None)
def fib_memo(n):
if n < 2:
return n
return fib_memo(n - 1) + fib_memo(n - 2)
With the cache, each Fibonacci number is computed once, so the number of calls grows in step with n. To compare how fast these two versions grow, the ideas in big o data structures are a good starting point.
Merge sort and quicksort
Both of these sorting methods use divide and conquer: split the problem, solve the parts recursively, and combine the results. The difference between that strategy and dynamic programming is covered in divide and conquer algorithm vs dynamic programming.
Merge sort splits a list in half, sorts each half, and merges the two sorted halves. Its running time is O(n log n) in every case. It is a stable sort, which means equal items keep their original order.
def merge_sort(items):
if len(items) <= 1: # base case: already sorted
return items
middle = len(items) // 2
left = merge_sort(items[:middle]) # recursive case: sort each half
right = merge_sort(items[middle:])
return merge(left, right) # combine the sorted halves
def merge(left, right):
result = []
i = 0
j = 0
while i < len(left) and j < len(right):
if left[i] <= right[j]: # <= keeps equal items in order
result.append(left[i])
i += 1
else:
result.append(right[j])
j += 1
result.extend(left[i:])
result.extend(right[j:])
return result
print(merge_sort([38, 27, 43, 3, 9, 82, 10])) # [3, 9, 10, 27, 38, 43, 82]
Quicksort picks a pivot value, separates the other items into smaller and larger groups, and sorts each group recursively. On average it runs in O(n log n) time, but a poor pivot choice can push it to O(n²).
def quicksort(items):
if len(items) <= 1: # base case
return items
pivot = items[0]
smaller = [x for x in items[1:] if x < pivot]
larger = [x for x in items[1:] if x >= pivot]
return quicksort(smaller) + [pivot] + quicksort(larger)
This version builds new lists, which is easy to read but uses extra memory. The textbook quicksort is an in-place algorithm: it swaps items within the original array, so it needs only a small amount of extra memory. Which sort is fastest overall depends on the data and the hardware, a question explored in what is the most efficient sorting algorithm.
The call stack and its limits
Each active call takes up a stack frame, which holds its arguments, its local variables and the place to return to. Frames pile up while calls are waiting, and they are removed as the base case returns. This is the same last-in, first-out order described in stack operations in data structure.
The deepest chain of calls determines how much stack memory is needed. Merge sort’s depth is about log2(n), because the list halves each time. A badly unbalanced quicksort can reach a depth close to n. Python’s default limit is 1,000 nested calls, so very deep recursion raises a RecursionError.
Recursive and iterative versions
Anything written recursively can be written with loops and an explicit stack, and most loops can be written as recursion. Loops usually use less memory and avoid depth limits. Recursion often matches the shape of the data more closely, especially for trees and nested folders. The factorial function, written with a loop, looks like this:
def factorial_loop(n):
result = 1
for number in range(2, n + 1):
result *= number
return result
Common mistakes
- Missing base case. Without one, the calls never stop.
- A recursive step that does not move toward the base case. Calling with n + 1 instead of n - 1 never reaches the base case.
- Repeated work. Naive Fibonacci solves the same subproblem many times. Memoization or a loop removes the repetition.
- Very deep recursion. Large inputs can exceed the stack limit. A loop or an explicit stack avoids that.
When recursion fits
Recursion fits problems that break naturally into smaller copies of themselves: trees, nested lists, folder structures, divide-and-conquer sorts, and backtracking searches such as finding a way through a maze. For a simple total over a flat list, a loop is usually clearer.
Key takeaways
- A recursive algorithm needs a base case and a recursive step.
- Classic examples include factorial, binary search, tree traversal, Tower of Hanoi, Fibonacci and merge sort.
- Each call uses stack memory, so the depth of recursion matters.
- Memoization removes repeated work, and a loop can replace recursion when depth becomes a problem.