While loop that halves n: why it is Θ(log n), step by step
A while loop that halves k each time runs ⌊log₂ n⌋ times. Counted step by step: 3⌊log₂ n⌋ + 4 ∈ Θ(log n).
The question
Consider the algorithm below, where n is the input size. Algorithm Halving (n) k <— n steps <— 0 WHILE ( k > 1 ) DO k <— k / 2 steps <— steps + 1 END WHILE RETURN steps END k / 2 is integer division. 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
Here the loop variable is halved every time, instead of going up by one. k / 2 is an integer division (the floor): 20 → 10 → 5 → 2 → 1.
How many halvings until k reaches 1? After m halvings k is about n / 2^m. It stops when n / 2^m = 1, so 2^m = n and m = log2 n (rounded down: ⌊log2 n⌋).
Before the loop, k <— n is one assignment.
And steps <— 0 is another.
The test k > 1 runs once per iteration plus once to exit: ⌊log2 n⌋ + 1 times.
One division per iteration: ⌊log2 n⌋ times.
One addition per iteration: ⌊log2 n⌋ times.
RETURN steps once.
Add the column: 3⌊log2 n⌋ + 4. The growing part is log n: ∈ O(log n). For n = 20 that is only 3·4 + 4 = 16 steps.
The rest
Next: the best case (Big Ω) and Big Θ, step by step, with a free account.