liveBook · Manning

Stopping criterion

As explained in Classic Computer Science Problems in Swift: Essential techniques for practicing programmers

The terminating condition of a recursive algorithm that can be solved directly without another recursive invocation.

A stopping criterion is the terminating condition that lets a recursive algorithm return a direct result instead of making another recursive call. In recursive Swift functions, it is usually expressed as a base case; without one, execution can continue indefinitely. section 1.1

A useful recursive design separates two cases:

  • Base case: recognize the smallest or directly solvable input and return its result. section 1.1 section 1.5
  • Recursive case: reduce a larger problem until a later call reaches the stopping criterion. section 1.5
  • Check every recursive path: a mathematically valid stopping condition does not prevent poor performance when calls branch repeatedly. section 1.1

Fibonacci

For Fibonacci, 0 and 1 are stopping values because they do not require adding earlier terms. A Swift implementation can test n < 2 and return n; larger values use fib2(n - 2) + fib2(n - 1). This prevents infinite recursion, although the naive branching version still performs many repeated calls. section 1.1

Towers of Hanoi

For Towers of Hanoi, moving one disc is the stopping criterion. Larger towers recursively move n - 1 discs, move the remaining disc, and move the n - 1 discs again. The base case therefore anchors each three-step decomposition. section 1.5

How Classic Computer Science Problems in Swift: Essential techniques for practicing programmers covers it

How deep it goes
Explains base and recursive cases with Fibonacci and Hanoi, then stops short of formal termination proofs.
Examples
Uses Fibonacci values and one-disc Towers of Hanoi moves as concrete stopping conditions.
What it assumes
Assumes basic Swift functions and recursion, while teaching how base cases terminate recursive algorithms.
What you can do after
Build recursive Swift functions by identifying direct inputs and separating them from recursive cases.
How it connects
Connects stopping criteria to recursion, infinite recursion, memoization, Fibonacci, and Towers of Hanoi.

Also explained in

Compare how 11 books explain stopping criterion →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Classic Computer Science Problems in Swift: Essential techniques for practicing programmers. The section links point to the parts of the book it draws on.