Algorithm Efficiency CS Thinking Example 2

Follow the full solution, then compare it with the other examples linked below.

Example 2

hard
Explain why binary search (O(logโกn)O(\log n)) is more efficient than linear search (O(n)O(n)) for a sorted list of 1,000,000 elements.

Solution

  1. 1
    Step 1: Linear search checks each element one by one: up to 1,000,000 comparisons in the worst case.
  2. 2
    Step 2: Binary search halves the search space each step: logโก2(1,000,000)โ‰ˆ20\log_2(1{,}000{,}000) \approx 20 comparisons.
  3. 3
    Step 3: Binary search is roughly 50,000 times faster for this input size.

Answer

Binary search needs ~20 comparisons vs 1,000,000 for linear search. O(logโกn)O(\log n) vastly outperforms O(n)O(n).
Logarithmic algorithms are extremely efficient because they eliminate half the remaining data each step. This is why keeping data sorted enables much faster searching.

About Algorithm Efficiency

The ratio of useful output energy (or power) to total input energy, expressed as a percentage โ€” always less than 100% due to energy losses.

Learn more about Algorithm Efficiency โ†’

More Algorithm Efficiency Examples