25.11.2014 Views

Algorithms and Data Structures

Algorithms and Data Structures

Algorithms and Data Structures

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

N.Wirth. <strong>Algorithms</strong> <strong>and</strong> <strong>Data</strong> <strong>Structures</strong>. Oberon version 99<br />

3 Recursive <strong>Algorithms</strong><br />

3.1 Introduction<br />

An object is said to be recursive, if it partially consists or is defined in terms of itself. Recursion is<br />

encountered not only in mathematics, but also in daily life. Who has never seen an advertising picture which<br />

contains itself?<br />

Fig. 3.1. A picture with a recursion<br />

Recursion is a particularly powerful technique in mathematical definitions. A few familiar examples are<br />

those of natural numbers, tree structures, <strong>and</strong> of certain functions:<br />

1. Natural numbers:<br />

(a) 0 is a natural number.<br />

(b) the successor of a natural number is a natural number.<br />

2. Tree structures:<br />

(a) ∅ is a tree (called the empty tree).<br />

(b) If t 1 <strong>and</strong> t 2 are trees, then the structure consisting of a node with two descendants t 1 <strong>and</strong> t 2 is<br />

also a (binary) tree.<br />

3. The factorial function f(n):<br />

f(0) = 1<br />

f(n) = n × f(n - 1) for n > 0<br />

The power of recursion evidently lies in the possibility of defining an infinite set of objects by a finite<br />

statement. In the same manner, an infinite number of computations can be described by a finite recursive<br />

program, even if this program contains no explicit repetitions. Recursive algorithms, however, are primarily<br />

appropriate when the problem to be solved, or the function to be computed, or the data structure to be<br />

processed are already defined in recursive terms. In general, a recursive program P can be expressed as a<br />

composition P of a sequence of statements S (not containing P) <strong>and</strong> P itself.<br />

P ≡ P[S, P]<br />

The necessary <strong>and</strong> sufficient tool for expressing programs recursively is the procedure or subroutine, for<br />

it allows a statement to be given a name by which this statement may be invoked. If a procedure P contains<br />

an explicit reference to itself, then it is said to be directly recursive; if P contains a reference to another<br />

procedure Q, which contains a (direct or indirect) reference to P, then P is said to be indirectly recursive.<br />

The use of recursion may therefore not be immediately apparent from the program text.

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!