This preview shows pages 1–3. Sign up to view the full content.
This preview has intentionally blurred sections. Sign up to view the full version.
View Full Document
Unformatted text preview: Duygu Karaoğlan 03.11.2009 6909 1 CS301 – Algorithms Homework 3 Question 1) Computing 2 n (a) Design a recursive algorithm for computing 2 n (for n > 1) based on the following formula:2 n = 2 n−1 + 2 n−1 , where 2 is known to be 1. However, suppose that you are using a funny programming language where no local variables can be defined and only the addition operation is allowed. int pow2 (int n ) { if( n == 0) return 1; else return pow2 ( n1) + pow2 ( n1); } (b) Set up a recurrence relation for the number of additions made by the algorithm and solve it. T(0) = 0, T(1) = 1, T(2) = 3, T(3) = 7 ... T( n ) = 2T( n1) + 1 = 2(T( n2) + 1) + 1 = 2T( n2) + 3 = 2(T( n3) + 3) + 1 = 2T( n3) + 7 = 2(T( n4) + 7) + 1 = 2T( n4) + 15 = 2(T( n5) + 15) + 1 = 2T( n5) + 31 ... = 2 n – 1 = O(2 n ) (c) Draw a tree of recursive calls for this algorithm and count the number of calls made by the algorithm. f(n) f(n1) f(n1) f(n2) f(n2) f(n2) f(n2) ... ... ... ... ... f(0) f(0) f(0) f(0) ... ... ... f(0) f(0) f(0) f(0) There are 2 n leaves of the tree represented above and f(0) = 1. Thus, the number of calls made by the algorithm is O(2 n ). Duygu Karaoğlan 03.11.2009 6909 2 (d) How would you modify the algorithm if the programming language allowed multiplication as well? Give the formula on which you would base your algorithm and the recurrence relation for the number of operations (addition and/or multiplication, whatever you are using in your algorithm) and solve the recurrence. int pow2 (int n ) { if( n == 0) return 1; else return 2* pow2 ( n1); } # of additions b none # of multiplications b T(0) = 0, T(1) = 1, T(2) = 2, T(3) = 3 ... T( n ) = T( n1) + 1 = T( n2) + 1 + 1 = T( n2) + 2 = T( n3) + 2 + 1 = T( n3) + 3 = T( n4) + 2 + 1 = T( n4) + 4 ... = T( n k ) + k Let n = k b T( n ) = T(0) + n = n = O( n ) Question 2) Discuss why the stable version of counting sort is stable. (Your answer shouldn’t be as simple as “We wouldn’t be calling it the stable version of counting sort if it weren’t stable”.) In the stable version of counting sort we have an array that holds how many times a number occurs and we have another array that holds the last occurance of a number. The sorting is performed by starting from the last element of the original array and at each replacement, the corresponding value of the second array, that holds the last occurance of a number, is...
View Full
Document
 Spring '10
 .
 Algorithms

Click to edit the document details