Lesson 3 of 19
Big O and counting comparisons
Find the highest score on a row of cards. Keep the best score so far and count each time you compare a new card with it. How does the count grow when the row gets longer?
Count every challenger to the maximum
Big O describes how the work grows with the input size. For a nonempty, unsorted array of n ordinary numbers, start with the first number and compare each remaining number with the best so far. The exact comparison count is n − 1. Adding one number adds one comparison, giving O(n) time and O(1) extra space.
Work through an example
Four jumps measure 2, 7, 4 and 9 metres. What is the longest jump, and how many comparisons find it?
Step-by-step solution
- Start with 2 as the longest jump. Reading the first distance gives you a starting value with zero comparisons.
- Compare 7 with 2 and keep 7. Compare 4 with 7 and keep 7 again. Both comparisons count.
- Compare 9 with 7 and keep 9. The longest jump is 9 metres after three comparisons.
JavaScript example
const jumps = [2, 7, 4, 9];
let max = jumps[0];
let comparisons = 0;
for (let i = 1; i < jumps.length; i++) {
comparisons++;
if (jumps[i] > max) max = jumps[i];
}
({ max, comparisons });DSA compiler
Try it yourself
Finish the animation to unlock this question.
The highest score is first in a row of six unsorted cards. How many score comparisons does the scan make?
Related exercise · Factorial · See this stage of the beginner path