Chapter 1
I
Introduction to algorithms
16
per second. With O(log
n
) time, it will take you 4 operations to draw a
grid of 16 boxes (log 16 is 4). So it will take you 0.4 seconds to draw
the grid. What if you have to draw 1,024 boxes? It will take you
log 1,024 = 10
operations, or 1 second to draw a grid of 1,024 boxes.
These numbers are using the first algorithm.
The second algorithm is slower: it takes O(
n
) time. It will take 16
operations to draw 16 boxes, and it will take 1,024 operations to draw
1,024 boxes. How much time is that in seconds?
Here’s how long it would take to draw a grid for the rest of the
algorithms, from fastest to slowest:
There are other run times, too, but these are the five most common.
This is a simplification. In reality you can’t
convert from a Big O run
time to a number of operations this neatly, but this is good enough
for now. We’ll come back to Big O notation in chapter 4, after you’ve
learned a few more algorithms. For now, the main takeaways are as
follows:
• Algorithm speed isn’t
measured in seconds, but in growth of the
number of operations.
• Instead, we talk about how quickly the run time of an algorithm
increases as the size of the input increases.
• Run time of algorithms is expressed in Big O notation.
• O(log
n
) is faster than O(
n
), but it gets a lot faster as the list of items
you’re searching grows.