Professional Documents
Culture Documents
IT2070 - Data Structures and Algorithms: Introduction To Recursion
IT2070 - Data Structures and Algorithms: Introduction To Recursion
1
SLIIT - Faculty of Computing
Data Structures and Algorithms
Recursion –Example 1
Factorial
A recursive definition is
2
Module Code | Module Name | Lecture Title | Lecturer
Data Structures and Algorithms
n * (n-1)! We know
0! So we
can build
(n-1) * (n-2)! the tree
backward
1!
1 * 0!
3
Module Code | Module Name | Lecture Title | Lecturer
Data Structures and Algorithms
Exercise
• Draw the recursive tree for 5!
• How does it calculate 5! ? Is it:
Bottom to top calculation or
Top to bottom calculation ?
5!
5 * 4!
4 * 3!
3 * 2!
2 * 1!
1 * 0!
initial
Module Code | Module Name | Lecture Title | Lecturer
condition 4
Data Structures and Algorithms
Factorial(contd.)
(n)! = {n * (n -1)! if n > 0}
{1 if n = 0}
Recursion
What is recursion?
A function that calls itself directly or indirectly to solve a smaller
version of its task until a final call which does not require a self-call is
a recursive function.
6
Module Code | Module Name | Lecture Title | Lecturer
Data Structures and Algorithms
Recurrence equation
• Mathematical function that defines the running
time of recursive functions.
7
Module Code | Module Name | Lecture Title | Lecturer
Data Structures and Algorithms
Recurrence - Example1
Find the Running time of the following function
int factorial(int n) {
if (n == 0) //A
return 1; //B
else
return (n * factorial(n -1)); //C
}
T(n) = a + c + T(n-1)
9
Module Code | Module Name | Lecture Title | Lecturer
Data Structures and Algorithms
Exercise
• Solve the recurrence
T(n) = T(n/2) + 2
You are given that
n = 16 and
T(1) = 1
• Other methods
• Recursion tree.
• Master Theorem.
T ( n ) ( n 2 )
Design & Analysis of AlgorithmsSri Lanka Institute of
19
Module Code | Module Information
Name Technology.
| Lecture Title | Lecturer
Data Structures and Algorithms
T (n) (log n)
Design & Analysis of AlgorithmsSri Lanka Institute of
20
Module Code | Module Information
Name Technology.
| Lecture Title | Lecturer
Data Structures and Algorithms
log4 3 0.2
Note : n lg n c.n .n
Design & Analysis of AlgorithmsSri Lanka Institute of
21
Module Code | Module Information
Name Technology.
| Lecture Title | Lecturer
Data Structures and Algorithms
Exercises.
• Use the master method to give tight asymptotic bounds
for the following recurrences.
1. T (n) = 4T(n/2) + n.
2. T (n) = 4T(n/2) + n2.
3. T (n) = 4T(n/2) + n3.
• Use the master method to show that the solution to the
binary-search recurrence T(n) = T (n/2) + Θ(1) is T(n) =
Θ(lg n).