comp108 time complexity of pseudo code. example 1 sum = 0 for i = 1 to n do begin sum = sum + a[i]...
TRANSCRIPT
COMP108Time Complexity of Pseudo Code
Example 1
sum = 0for i = 1 to n dobegin sum = sum + A[i]endoutput sum
O(n)
Example 2
sum = 0for i = 1 to n do sum = sum + A[i]output sumproduct = 1for i = 1 to n do product = product * A[i]output product
O(n)
Example 3
sum = 0for i = 1 to n dobegin for j = 1 to n do begin sum = sum + i * j endendoutput sum
O(n2)
Example 4
sum = 0for i = 1 to n dobegin for j = 1 to m do begin sum = sum + i * j endendoutput sum
O(nm)
Example 5
sum = 0for i = 1 to n do for j = 1 to n do for k = 1 to n do sum = sum + i * j * koutput sum
O(n3)
Example 6
i = 1while i <= n dobegin output i i = i * 2end
i = n
while i > 1 do
begin
output i
i = i / 2
end
O(log n)
Example 7
i = 1while i <= n dobegin j = 1 while j <= n do begin output i*j j = j * 2 end i = i + 1end
O(n log n)
Graph - Example 1// Input: a graph G=(V,E) with n vertices and m edges
V' = while V' ≠ V dobegin pick a new vertex v in V \ V' V' = V' {v}end
O(n)
Graph - Example 2// Input: a graph G=(V,E) with n vertices and m edges
V' = Vwhile V' ≠ dobegin pick a new vertex v in V' V' = V' \ {v}end
O(n)
Graph - Example 3// Input: a graph G=(V,E) with n vertices and m edges
E' = while E' ≠ E dobegin pick a new edge e in E \ E' E' = E' {e}end
O(m)
Graph - Example 4// Input: a graph G=(V,E) with n vertices and m edges
E' = Ewhile E' ≠ dobegin pick a new edge e in E' E' = E' \ {e}end
O(m)
Graph - Example 5// Input: a graph G=(V,E) with n vertices and m edges
V' = for each vertex v in V dobegin unmark vendwhile V' ≠ V dobegin pick an unmarked v in V mark v V' = V' {v}end
O(n)
Graph - Example 6// Input: a graph G=(V,E) with n vertices and m edges
V' = while V' ≠ V dobegin pick a new vertex v in V \ V' V' = V' {v} for every neighbour u of v do begin output information of u endend
O(n2)
Graph - Example 7// Input: a graph G=(V,E) with n vertices and m edges
V' = for each vertex v in V dobegin initalise information of vendwhile V' ≠ V dobegin pick a new vertex v in V \ V' V' = V' {v} for every neighbour u of v do begin output information of u endend
O(n2)
Graph - Example 8// Input: a graph G=(V,E) with n vertices and m edges
E' = while E' ≠ E dobegin pick a new edge e=(u,v) in E \ E' E' = E' {e} for every vertex w in V do begin if w is a neighbour of u or neighbour of v then output information of w endend
O(nm)