Quiz Entry - updated: 2026.09.18
Count the primitive operations of arrayMax, which finds the largest element of an array of $n$ integers.
Worst case $8n-2$: two for the initial assignment, $1 + 2n$ for the loop control, three two-operation statements for each of the $n-1$ iterations, and one for the return.
Algorithm arrayMax(A, n) # operations
currentMax ← A[0] 2
for i ← 1 to n − 1 do 1 + 2n
if A[i] > currentMax then 2(n − 1)
currentMax ← A[i] 2(n − 1)
{ increment counter i } 2(n − 1)
return currentMax 1
Total (worst case): 8n − 2
Reading the tricky lines:
currentMax ← A[0]costs 2: one index into the array, one assignment.- The
forheader costs 1 + 2n: one initialisation, then for each of the $n$ tests a comparison and its evaluation. Note the loop test runs once more than the body — the final test is the one that fails. - Each of the three body lines costs 2 and runs $n-1$ times, hence $3 \cdot 2(n-1)$.
returncosts 1.
Summing: $2 + (1 + 2n) + 6(n-1) + 1 = 8n - 2$.
The individual numbers matter far less than the shape: whatever you decide an array index "really" costs, the total stays of the form $an + b$ — linear. That is the result that survives, and it is the only one the O-notation will keep.