Time complexity of finding the maximum: IF inside a loop, step by step
Find the maximum of an array and count it: the IF costs the condition plus its bigger branch. Worst case 4n, best case 3n + 1, both Θ(n).
The question
Consider the algorithm below, where n is the input size. Algorithm MaxNumber (A, n) Max <— A[0] FOR i <— 1 to n-1 DO IF ( A[i] > Max ) Max <— A[i] END IF END FOR RETURN Max END n ≥ 1. Part 1: Find the worst-case time complexity (Big O). Part 2: Find the best-case time complexity (Big Ω). Part 3: Find Big Θ.
Worked solution
This loop always runs, but the IF decides whether Max <— A[i] happens. For an IF we add the cost of the condition and the cost of the bigger branch. The worst case is when that branch runs every time: an increasing array like 1, 3, 5, 8.
Max <— A[0] is one assignment.
The loop starts once: i <— 1.
i goes from 1 to n-1: that is n-1 iterations, so the test runs n-1 times plus one extra exit check: n times.
The FOR moves i on after each iteration: n-1 times.
The condition A[i] > Max is checked in every iteration: n-1 times.
In the worst case every element is a new maximum, so the branch Max <— A[i] runs every time: n-1 times.
RETURN Max runs once.
Add the column: 1 + 1 + n + (n-1) + (n-1) + (n-1) + 1 = 4n. So 4n ∈ O(n).
The rest
Next: the best case (Big Ω) and Big Θ, step by step, with a free account.