Linear search time complexity: worst, best and average case, step by step

Linear search counted step by step: worst case 3n + 3 ∈ O(n), best case Ω(1), and Big Θ from the average case with probabilities and the summation rule.

The question

Consider the algorithm below, where n is the input size. Algorithm LinearSearch (A, n, b) FOR k <— 0 to n-1 DO IF ( A[k] == b ) RETURN k END IF END FOR RETURN -1 END b is the value being searched for. 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

Big O is the worst case: the most work. For a search, that is when b is not in the array, so the loop checks every element and never returns early.

The loop starts once: k <— 0.

The test k ≤ n-1 runs for k = 0 … n-1 (n times), plus one extra check when k = n, the one that exits: n+1 times.

After each of the n iterations, the FOR moves k on: n increments.

The comparison A[k] == b runs once per iteration, and in the worst case it is false every time: n times.

RETURN k only runs when b is found. In the worst case: 0 times.

The loop ends without finding b, so RETURN -1 runs once.

Add the column: 1 + (n+1) + n + n + 0 + 1 = 3n + 3. Keep the fastest-growing term: 3n + 3 ∈ O(n).

The rest

Next: the best case (Big Ω) and Big Θ, step by step, with a free account.