week3 - EECS 280 Week 3 Discussion Notes Tail Recursion and...

Info iconThis preview shows pages 1–2. Sign up to view the full content.

View Full Document Right Arrow Icon
EECS 280 Week 3 Discussion Notes Tail Recursion and Function Pointers 1 Tail Recursion As we have seen last week, recursion is an important concept in computer science–it is the basis of many important constructs (e.g. binary trees), and algorithms (e.g. quicksort). Those who have seen “mathematical induction” will notice the similarities of the two concepts. The basic idea is to solve the problem for some small cases and provide a recipe for transforming larger instances of the problem into smaller ones. Usually a recursive function consists of the following components: Base Case(s) This gives the solution to the small cases of the problem. This is usually put at the beginning of the recursive function, so we do not get into a recursive call. Pre-processing This step transforms larger instances of the problem into smaller ones. Recursive Call(s) This is the recursive step, the function calls itself on smaller inputs. Post-processing This step takes the solution from the recursive call(s) and combine them to provide a solution to the original input. Let us analyze the factorial function to see how the components fit together. int f a c t o r i a l ( int n) { i f ( ! n) { return 1; } else { return (n * f a c t o r i a l (n - 1)); } } Here the base case is when n==0 , where factorial(0)=1 . The pre-processing is the fact that we can compute n ! from ( n - 1)!. So we recursively call factorial with input n-1 . The post-processing step is given the value of ( n - 1)! we multiply it with n to get n !. Another interesting example is that of merge sort. The problem is given a list (array) of numbers, to output a sorted list. The approach for merge sort is to divide the list in half (pre- processing), perform merge sort on each half of the list (recursive calls), and then merge the two sorted list together (post-processing). The base case is a list with one elements is already a sorted list, so nothing needs to be done. From lecture we learned that to perform a recursive computation we needed to store infor-
Background image of page 1

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
Image of page 2
This is the end of the preview. Sign up to access the rest of the document.

This note was uploaded on 04/04/2008 for the course EECS 215 taught by Professor Phillips during the Winter '08 term at University of Michigan.

Page1 / 4

week3 - EECS 280 Week 3 Discussion Notes Tail Recursion and...

This preview shows document pages 1 - 2. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online