Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 1

Data Structures (CS-201) Spring 2019 Quiz # 1 Roll-No: --------------------------- Sec:--------

Q#1: Find the Time complexity T(n) and Big-O of the following piece of code and show all working.
int sum = 0;
for (int i = 4; i < n; i++) {
for (int j = i-3, sum = a[i-4]; j <= i; j++)
sum += a[j];
cout<<”Sum=”<<sum<<end1;
}
Statements Cost Frequency Cost* Frequency
int sum = 4; 1 1 1

int i = 4; 1 1 1
i < n 1 n-4 +1 n-3
i++ 2 n-4 2n-8

int j = i-3 2 n-4 2n-8


sum = a[i-4] 2 n-4 2n-8
j <= i 1 n-4 ( 4 ) 4n-16
j++ 2 n-4 (4) 8n-32

sum += a[j]; 2 n-4 (4) 8n-32

cout<<”Sum=”<<sum<<end1; 1 n-4 n-4

T(N) = 28n – 109

O(N)

Outer loop runs n-4 times


Inner loop runs constant time 4 times for each iteration of outer loop.
i=4
j = 1, 2, 3, 4, 5 4 times
i=5
j = 2, 3, 4, 5, 6 4 times
i=6
j = 3, 4, 5, 6, 7 4 times

You might also like