Counting Operations in a Small Algorithm

A cost model names the operations it counts and treats the resulting count as a function of input size.

Source
Anbloq
Language
English
Created
Updated
Chapters
4
Reading time
1 min
In this article4 chapters
  1. Choose a relevant operation
  2. Connect the count to the model
  3. Count two kinds of work on the same input
  4. Choose a cost model that fits the operation

Choose a relevant operation

In a scan of four readings for a fixed value, a worst case performs four comparisons with that value. Reading elements and updating an index add their own work. A first-match scan gives the precise point where comparisons stop.

Connect the count to the model

If comparisons operate on arbitrarily long strings, each can cost more than one character comparison. Define the input units before claiming a time bound. Asymptotic input models give examples with several varying dimensions.[1]

Count two kinds of work on the same input

A running maximum starts from the first value and compares each remaining value once. For [2, 8, 5, 9, 1] the comparisons count four. The maximum changes twice after initialization. Other orders can change the number of assignments without changing the number of comparisons. See finding both extremes.

Read 2 → initialize
Compare 8 with 2 → update
Compare 5 with 8 → keep
Compare 9 with 8 → update
Compare 1 with 9 → keep

Choose a cost model that fits the operation

Elements with very long integer representations can make one mathematical comparison more expensive than another. When reporting \(n-1\) comparisons, state that \(n\) counts elements, then explain any assumption that turns the count into a runtime.

References

  1. Jeff Erickson, Algorithms ↩