

Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!


Worksheet 11: Recursive Functions and Recurrence Relations Name:
In Preparation : Read the section on recursive functions and recurrence relations in Chapter 4. As described in Chapter 4, a very useful technique for analyzing recursive functions is to form recurrence relations. For example, suppose we are analyzing the function shown at left. Let n will represent the number of binary digits in the printed form. Because the argument is divided by 2 prior to the recursive call, it will have one fewer digit. Everything else, outside of the recursive call, can be performed in constant time. The base case can also be performed in constant time. If we let T(n) represent the time necessary to print an n-digit number, we have the following equation: T(n) = T(n-1) + c T(1) = c Read this as asserting that the time for n is equal to the time for n-1 plus some unknown constant value. This is termed a recurrence relation. The four most common recurrence relations and their solutions are shown at left. The following are some example recursive functions. Describe the running time for each as a recurrence relation, and then give the big-Oh execution time: factorial(int n) { if (n = 0) return 1; else return n * factorial(n-1) } double exp (double a, int n) { if (n == 0) return 1.0: else return a * exp (a, n-1); } void Hanoi (int n, int a, int b, int c) { if (n > 0) { T(n) = T(n-1) + c O(n) T(n) = T(n/2) + c O(log n) T(n) = 2 * T(n/2) + ca n + cb O(n log n) T(n) = 2 * T(n-1) + c O( n ) void printBinary (int v) { if ((v == 0) || (v == 1)) print(n); else { printBinary(v/2); print(v%2); } }
Worksheet 11: Recursive Functions and Recurrence Relations Name:
Hanoi(n-1, a, c, b); System.out.println(“Move from “ + a + “ to “ + b + “using “ + c); Hanoi(n-1, c, b, a); } } For the following, let n represent the size of the region of the array between low and high int binarySearch (double data[ ], int low, int high, double test) { if (low == high) return low; int mid = (low + high)/2; if (test < data[mid]) return binarySearch(data, low, mid, test) else return binarySearch(data, mid, high, test); }