In the previous post, we have studied, Complexity Analysis of Common Loops,
As you go through this, the journey of understanding Data Structures, to make your code more efficient you will use the concept of Recursion.
When we analyze these functions, we get a recurrence relation for time
complexity. For example in Binary Search, to search a given element, we divide the array/list into two halves and recursively repeat the process for two halves, until we get the element we are searching for. The time complexity of
Binary Search is T(n) = T(n/2) + c i.e., Ө(log n). There are many such algorithms like Tower of Hanoi, Josephus Problem, and many more.
We have three methods, for calculating the Complexity of the Recursive
Function.|
1) Substitution methods
2) Tracing Tree Methods
3)
Master Theorem
First, let's take a simple example,
void Test(int n) { --- T(n) if (n < 0) { printf("%d", n); --- 1 Test(n-1); --- T(n-1) } }So, we have time Complexity function T(n) = T(n-1)+1
Test(3) -- 1 unit of time
/ \
print(2) Test(1) --- 1 unit of time
/ \
|
where n is the number of prints,
Simirally, T(n) = [T(n-3)+1] +2
:
- If the cost of solving the sub-problems at each level is increased by a certain factor, the value of f(n) will become polynomially smaller than nlogb a. Thus the time complexity is oppressed by the cost of the last level i.e., nlogb a.
- If the cost of solving the sub-problem at each level is nearly equal, then the value of f(n) will be nlogb a. Thus the time complexity will be f(n) times the total number of levels i.e., nlogb a * log n.
- If the cost of solving the sub-problems at each level decreases by a certain factor, the value of f(n) will become polynomially larger than nlogb a. Thus, the time complexity is oppressed by the cost of f(n).
Subscribe by Email
Follow Updates Articles from This Blog via Email
No Comments