computational complexity exercise
-
21-08-2019 - |
Question
I'm reading "Data structures and algorithms" from Aho, Hopcroft & Ullman, and I'm confused with exercise 1.12 B:
Which is the computational complexity (expressed in Big O notation) of this Pascal procedure?
procedure mysterious( n: integer );
var
i, j, k: integer;
begin
for i := 1 to n - 1 do
for j := i + 1 to n do
for k := 1 to j do
{mysterious statement of O(1)}
end
Could you please help me?
Thanks!
Solution
It's O(n3). The big-O shows how execution time (or memory or whatever) is proportional to the size of the task (the proportionality coefficient is omitted).
In this cases the inner statement is executed times proportional to (n3). i runs from 1 to (n-1) - so everything inside the outer cycle is executed (n-1) times. j runs on average from (n/2) to (n) - so everything inside is executed (n-1)* (n/2) times. k runs on average from 1 to (3/4* n). This gets (n-1)* (n/2)* (3/4*n-1) executions of the inner statement. This is O(n3).