CSE302: Data Structures Using C: DR Ashok Kumar Sahoo 9810226795
CSE302: Data Structures Using C: DR Ashok Kumar Sahoo 9810226795
Recursive program:
int main()
{
int n=10;
printf(“%d”, rfib(n));
}
int rfib(int n)
{
if (n==1 || n==2) return 1;
return rfib(n1)+rfib(n2);
}
Performance Analysis
• Space Complexity: The space complexity
of a program is the amount of memory
it needs to run to completion.
• Time Complexity: The time complexity
of a program is the amount of computer
time it needs to run to completion.
Space Complexity
• A fixed part that is independent of the
characteristics of the inputs and outputs. This part
typically includes the instruction space, space for
simple variables and fixed-size component
variables, space for constants, etc.
• A variable part that consists of the space needed by
component variables whose size is dependent on the
particular problem instance being solved, the space
needed by referenced variables, and the recursion
stack space.
Time Complexity
• The time taken by a program is the sum
of the compile time and the run (or
execution) time.
• The compile time does not depend on the
instance characteristics.
• We focus only on the run time of a
program.
Fibonacci Numbers
• The Fibonacci sequence of numbers
starts as 0, 1, 1, 2, 3, 5, 8, 13, 21, 34,
55, …
• Each new term is obtained by taking the
sum of the two previous terms. If we
call the first term of the sequence F0
then F0 = 0, F1 = 1, and in general,
• Fn = Fn-1 + Fn-2 , n ≥ 2.
C Program of Fibonacci Numbers
1. void fibonacci (int n)
2. // compute the Fibonacci number Fn
{
3. int fn; int fnm2 = 0; int fnm1 = 1;
4. if (n <= 1) printf(“%d\n”, n); // F0 = 0, and F1 = 1
5. else { // compute Fn
6. for (int i = 2; i <= n; i++)
7. {
8. fn = fnm1 + fnm2;
9. fnm2 = fnm1;
10. fnm1 = fn;
11. } // end of for
12. printf(“%d\n”, fn);
13. } // end of else
14. } // end of fibonacci
Step Count
Line # Execution times Remarks
1 Function invocation -
2 - Opening Bracket
3 One Initialization
4 Two n=0, n=1
5 n-1 Else
6 n-1 For loop
7 - Opening Bracket
8 n-1 fn = fnm1 + fnm2;
• 3n + 2 = O(n)
3n + 2 ≤ 4n for all n ≥ 3
• 100n + 6 = O(n)
100n + 6 ≤ 101n for all n ≥ 10
• 10n2 + 4n + 2 = O(n2)
10n + 4n + 2 ≤ 11n for all n ≥ 5
2 2
[Big “oh”]
= n0
Asymptotic Notation (Cont.)
log n n n log n n2 n3 2n
0 1 0 1 1 2
1 2 2 4 8 4
2 4 8 16 64 16
3 8 24 64 512 256