(Lab-5 Manual) CS-204-DSA - Time Complexity Analysis
(Lab-5 Manual) CS-204-DSA - Time Complexity Analysis
Fall 2019
Lab-4 Manual
Time Complexity Analysis using Big-Oh
v1.0
4/4/2019
Lab-4 Manual 2019
Performance Analysis
Introduction:
Performance Analysis of Algorithms and Data Structures is carried out in terms of:
1) Space complexity.
2) Time complexity.
Space Complexity of a program is the amount of memory it needs to run to completion.
Time Complexity of a program is the amount of computer time it needs to run to completion.
There are two methods to determine the performance of a program, one is analytical, and the other
is experimental.
Asymptotic Notation:
Asymptotic analysis of an algorithm or data structure refers to defining the mathematical
boundaries of its performance. Using asymptotic analysis, we can conclude the best case, average
case, and worst-case scenario of an algorithm. The BIG-Οh is the formal way to express the upper
bound or worst-case of a program’s time and space complexity.
Analytical Analysis:
Analytically finding time complexity of the following code:
int sum, i, j;
sum = 0;
for (int i = 0 ; i< n ; ++i)
{ for(int j=0 ; j<n ; ++j)
{ sum++;
}
}
Result:
Statement Number of times executed
sum=0 1
i=0 1
i<n n+1
++i N
j=0 N
j<n n(n+1) = n2 + n
++j n2
sum++ n2
Total 3n2+4n+3
T(n) = 3n2+4n+3, T(n) = O(n2)
Page 1
Lab-4 Manual 2019
T(n) = T(n) =
Big O = Big O =
public void Code3(long n){ public void Code4(long n){
int sum,i,j; int sum,i,j;
sum = 0; sum = 0;
for (i=1;i<n; ++i) for (i=0;i<n;++i)
{ {
for (j=0;j<i;++j) for (j=0;j<n;++j)
{ sum++; { sum++;
} }
} }
} }
T(n) = T(n) =
Big O = Big O =
public void Code6(long n){
public void Code5(long n){ int sum,i,j;
int sum,i,j; sum = 0;
sum = 0; for (i=1;i<n; i=i*2)
for (i=1;i<n; i=i*2) {
{ for (j=0;j<n;++j)
for (j=0;j<i; j++) {sum++;
}
{ sum++; }
} }
}
}
T(n) = T(n) =
Big O = Big O =
Table 1
Page 2
Lab-4 Manual 2019
Experimental Analysis:
To find time complexity of a code experimentally we need to calculate the time difference
between starting and ending time of execution of code. So to take the time in java we use
System.currentTimeMillis()method which will return us the current time of type
long in milliseconds.
We will use Thread.sleep(1000) method to make an delay of one second in our program.
Thread.sleep() requires time in milliseconds of type long. Where 1 second is equal to
1000 milliseconds so Thread.sleep(1000) will make an pause of 1 second in program.
Code mentioned below is used to calculate the actual running time of the Code which maybe
different on every computer due to their processor and clock speed.
long startTime;
startTime = System.currentTimeMillis();
Thread.sleep(1000);
for(int i=0;i<100000;i++){}
long endTime;
endTime = System.currentTimeMillis();
}//main
}//TimeTest
NOTE: Copy the TimeTest.java code from the Code folder then compile and run the code.
Page 3
Lab-4 Manual 2019
Figure 1
Page 4