CS 112
Lecture 13
Recursion
- Recursive definitions: refer to themselves. Example: definition for fully
parenthesized arithmetic expressions.
- A recursive function is defined in such a way that it refers to itself
within its own definition. A recursive program is an implementation (in some
programming language) of a recursive function.
- Simple examples: factorial, sum of the first n integers,
fibonacci function. More elaborate examples: Towers of Hanoi,
and others to be done next time (sorting).
- Short lab session: everybody implements the factorial function.
- Extra examples (to look at after class); Sum,
a function to add all the numbers in an array. If n is 0, it returns the a[0].
Otherwise, it adds a[n] to the sum of the first (n-1) elements, computed
recursively. Do you hear the self-reference in this description? Here
is an implementation in C++.
- How a recursive function call is evaluated. Trace the stack during the
function call for sum(4) and fib(4).
- More examples later: a recursive function implementing a recursive
definition. A function testing whether a given arithmetic expression (given as
a string of characters) is in prefix
form (code not available, but we will discuss it in class).
- When to use recursive functions? When you "hear" the recursive reference
in the very description of the function.
- Recursive algorithms: a very powerful technique of algorithm design.
Sometimes it produces very efficient algorithms.
- A few recursive definitions that you might "hear": the factorial function
(product of the the first n numbers); finding the minimum element of an array;
searching in an array; binary search.
- Simple recursive definitions for: finding the minimum, searching an
element in an array, sequentially and by binary search; adding all elements of
an array. Here is Sum,
a function to add all the numbers in an array a. If n is 0, it returns a[0].
Otherwise, it adds a[n] to the sum of the first (n-1) elements, computed
recursively.
- Quick Sort, a "divide-and-conquer" recursive algorithm for sorting.
I will explain it, and we will trace its execution in class on a few examples.
Discussion Hwk 6
In-class exercises: allocation of variables
Ileana Streinu