Professional Documents
Culture Documents
CO2226: Algorithm Design and Analysis Tutorial 6 Time Complexity
CO2226: Algorithm Design and Analysis Tutorial 6 Time Complexity
Tutorial 6
Time Complexity
1.
b)
c)
1: i n, j n
2: while i 1 do
3: for j 1; j < n ; j j + 1 do
4:
x x+1
5: end for
6: i i div 2
7: end while
CO2226 Tut 6
3.
Analyse the following segments of programs in terms of the big-O notation in (1)
the worst case (2) the best case. Justify your solutions.
a) Calculate mean
n=0
sum=0
input(x)
while x!=-999 do
n=n+1
sum=sum+x
input(x)
end {while}
mean=sum/n
b) Bubble sort
for i=1 to n-1 do
for j=i to n-1 do
if x[j]>x[j+1] then
temp=x[j]
x[j]=x[j+1]
x[j+1]=temp
end {if}
end {for}
end {for}
4. a)
b)
f(n) = n2n
ii.
g(n) = 3n
Discuss briefly the time complexity in the worst case for the algorithm below.
Indicate the basic operations you have counted.
1: for i 1; i < 2n ; i i + 1 do
2:
for j 1; j < i ; j j + 1 do
3:
for k 1;k < i ; k k + 1 do
4:
xx +1
5:
end for
6:
end for
7: end for
CO2226 Tut 6