130 likes | 225 Views
Foundations of Data Structures. Practical Session #3 Recurrence. Solution Methods. Substitution method Guess the form of the solution and prove it by induction. Iteration method Convert the recurrence into a summation and solve it Master method Next practical session….
E N D
Foundations of Data Structures Practical Session #3 Recurrence Amihai Savir & Ilya Mirsky - 2013
Solution Methods • Substitution method • Guess the form of the solution and prove it by induction. • Iteration method • Convert the recurrence into a summation and solve it • Mastermethod • Next practical session…
Question 0- warm up • Find the most tight asymptotic relation between the following pairs: • )
Question 1 Prove that using the substitution method. Solution The form of the solution is already given, so we don't have to guess it. We only need to prove that, i.e., that .
Question 3 fact(n) { if (n == 0) return 1 return n * fact(n – 1) }
Question 4 • Fibonacci series is defined as follows: • Find an iterative algorithm and a recursive one for computing element number in Fibonacci series, i.e., Fibonacci(n).Analyze the running-time of each of the algorithms.
Question 4 cont’d recFib(n) { if (n ≤ 1) return n else return recFib(n-1) + recFib(n-2) }
Question 4 cont’d • In the same manner: • The series ends when • To summarize:
Question 4 cont’d iterFib(n) { allocate f[0..n] f[0] = 0 f[1] = 1 for (i=2 ; i ≤ n ; i++) f[i] = f[i-1] + f[i-2] return f[n] }
Question 5 • publicstaticintfindMax(int[]arr) } • returnFindMax(arr,0, arr.length-1); • { • public staticintfindMax(inta[],intleft, intright)} • intmiddle; • intmax_l, max_r; • if( left == right ) • returna[left]; • else } • middle = (left + right) / 2; • max_l= FindMax( a, left, middle); • max_r= FindMax( a, middle+1, right); • returnMath.max(max_l,max_r); • { • {