Download as pdf or txt
Download as pdf or txt
You are on page 1of 2

CO2226 : Algorithm Design and Analysis

Tutorial 6
Time Complexity
1.

What is the time efficiency of an algorithm, in terms of the big-O notation, if it


always requires 1000,000,000 basic operations ?

Discuss the time complexity for the following algorithms :


a) int j=0;
for (int i=0; i<N; i++) {
while ( (j<N-1) && (A[i]-A[j] > D) )
j++;
if (A[i]-A[j] == D) return 1;
}

b)

Algorithm insertionsort(int array[0..n-1])


1: for i 1, i n 1, i + + do
2:
current array[i]
3:
position i 1
4:
while position 0 and current < array[position] do
5:
array[position + 1] array[position]
6:
position position 1
7:
end while
8:
array[position + 1] current
9: end for

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)

Consider the two functions below. Indicate whether f= O(g), or f = (g), or f =


(g). Justify your answer and show all your work
i.

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

You might also like