Transcript
Two programs search the same sorted list of a million names, on the same computer. Both find the answer. One of them looked at a million names. The other looked at twenty. Make the list a billion names long, and the gap grows to more than thirty million times. Today: how programmers measure fast.
An algorithm is a fixed list of steps that solves a problem, every time, for any input. Here's the first one. Start at the top, look at each name, and stop when you find it. Simple, and always correct. The second one needs the list to be sorted. Look at the middle name. If yours comes later, throw away the whole first half. Then do it again with what's left: half, half, half, until one name is left. We'll take this one apart in episode five.
Which one is faster? A stopwatch isn't fair. A newer computer, or a busier one, changes the time. So we count steps instead. Call the number of names n. For the first program, the worst case is checking every single name. n names, n steps. For the second, every step cuts the list in half. A million halves down to one in twenty steps, because two to the twentieth is just over a million. Now watch what happens as the list grows. A thousand names: a thousand steps, or ten. A million: a million, or twenty. A billion: a billion, or thirty. A thousand times more names costs the second program just ten more steps.
Programmers write this growth with a capital O. The first program is O of n: double the names, double the work. The second is O of log n: double the names, and it takes just one more step. Big O ignores the small stuff. A program that takes three n plus five steps is still O of n: for big n, the five hardly matters, and neither does the three. What matters is the shape of the curve. n log n is as fast as good sorting gets. We'll get there in episode seven. n squared is what you get when every item is compared with every other item. For a million items, that's a million million steps: about seventeen minutes, even at a billion steps a second. And two to the n doubles with every single item you add. With just a hundred items, it would take about forty trillion years.
Time isn't the only cost. Memory is another. Often you can trade one for the other: keep an extra table in memory, and finding things gets faster. We'll do exactly that in episode ten.
So, to compare algorithms: count the steps, and watch how they grow. Which brings us to a first question for any algorithm: where does the data actually live? Next time: arrays and linked lists. See you there.
Next episode: arrays and linked lists, the two oldest ways to keep data in memory.