Unit 1
Unit 1
n n n n n
i 1 j i
1 (n i 1) (n 1) i
i i 1 i 1
n(n 1) n(n 1)
n(n 1) n2
2 2
Recursion
• A recursive procedure can often be analyzed
by solving a recursive equation
• Basic form:
T(n) = if (base case) then some constant
else ( time to solve subproblems +
time to combine solutions )
• Result depends upon
– how many subproblems
– how much smaller are subproblems
– how costly to combine solutions (coefficients)
Example: Sum of Integer Queue
sum_queue(Q){
if (Q.length == 0 ) return 0;
else return Q.dequeue() +
sum_queue(Q); }
– One subproblem
– Linear reduction in size (decrease by 1)
– Combining: constant c (+), 1×subproblem
Equation: T(0) b
T(n) c + T(n – 1) for n>0
Sum, Continued
Equation: T(0) b
T(n) c + T(n – 1) for n>0
Solution:
T(n) c + c + T(n-2)
c + c + c + T(n-3)
kc + T(n-k) for all k
nc + T(0) for k=n
cn + b = O(n)
Example: Recursive Fibonacci
• Recursive Fibonacci:
int Fib(n){
if (n == 0 or n == 1) return 1 ;
else return Fib(n - 1) + Fib(n - 2); }
• Running time: Lower bound analysis
T(0), T(1) 1
T(n) T(n - 1) + T(n - 2) + c if n > 1
• Note: T(n) Fib(n)
• Fact: Fib(n) (3/2)n
O( (3/2)n ) Why?
Direct Proof of Recursive
Fibonacci
• Recursive Fibonacci:
int Fib(n)
if (n == 0 or n == 1) return 1
else return Fib(n - 1) + Fib(n - 2)
3 4
2 3
1 2
1 2
0 1
0 1
0 1
Efficient Fibonacci: A Trace
Performance is O(n)
9
Recursive Definitions: Power
• x0 = 1
• xn = x xn-1
Chapter 7: Recursion 10
Recursive Definitions: Factorial Code
public static int factorial (int n) {
if (n == 0) // or: throw exc. if < 0
return 1;
else
return n * factorial(n-1);
}
Chapter 7: Recursion 11
Another example
• The factorial function: multiply together all
numbers from 1 to n.
• denoted n!
n!=n*(n-1)*(n-2)*…2*1
T(n) T(n/2) + c
T(n/4) + c + c
T(n/8) + c + c + c
T(n/2k) + kc
T(1) + c log n where k = log n
b + c log n = O(log n)
Example: MergeSort
Split array in half, sort each half, merge together
– 2 subproblems, each half as large
– linear amount of work to combine
T(1) b
T(n) 2T(n/2) + cn for n>1
Chapter 7: Recursion 29
Searching
Definition
• Easy to implement
• In-place sort (requires no
additional storage space)
Disadvantages
• It works by iterating the input array from the first element to the last,
comparing each pair of elements and swapping them if needed.
• Bubble sort continues its iterations until no more swaps are needed.
• The algorithm gets its name from the way smaller elements “bubble”
to the top of the list.
• The only significant advantage is that it can detect whether the input
list is already sorted or not.
Implementation
• Algorithm takes O(n2) (even in best case).
• We can improve it by using one extra flag.
• No more swaps indicate the completion of
sorting. If the list is already sorted, we can use
this flag to skip the remaining passes.
Performance