Find a course

Module 2: Algorithms and ProgrammingLesson 6 of 1113 min

Algorithms, Search and Efficiency

Compare linear and binary search, tell reasonable from unreasonable running times, and learn when heuristics help and why some problems are undecidable.

Step 1 of 10Learn

Same problem, different algorithms

An algorithm is a finite set of instructions that accomplishes a task. Usually there are many algorithms for the same problem, and some are far faster than others.

Take searching. Suppose you need to find a name in a list of 1,000 students.

Linear search (sequential search) checks elements one by one from the start until it finds the target or reaches the end. It works on any list, sorted or not. In the worst case, when the name is last or missing, it checks all 1,000.

Binary search only works on a sorted list, but it's dramatically faster. Check the middle element. If it's the target, you're done. If the target comes earlier alphabetically, throw away the second half; otherwise throw away the first half. Repeat on what remains. Each check halves the list: 1,000, then 500, 250, 125, 63, 32, 16, 8, 4, 2, 1. Even in the worst case, about 10 checks are enough.

Double the list to 2,000 students and linear search may need 2,000 checks, while binary search needs just one more, 11. That's the power of halving: the number of steps grows with the logarithm of the size, which grows very slowly.

The catch is sorting. If the data isn't already sorted, you must sort it first, which takes time. For one search on unsorted data, linear search may be the practical choice; for many searches, sorting once and then using binary search pays off.

Step 2 of 10Explore

Linear search vs binary search

The chart shows the worst-case number of checks for a list of x items. The straight line is linear search; the flat curve is binary search. Use the slider to read off the values for a specific list size.

2004006008001,000 2004006008001,000
Linear search, worst case
1,000
Binary search, worst case
10

Step 3 of 10Practice · Work it out

A sorted list has 64,000 entries. About how many checks does binary search need in the worst case? (Use the smallest n with 2n greater than 64,000.)

Step 4 of 10Learn

Reasonable and unreasonable time

Computer scientists describe efficiency by how the number of steps grows as the input size n grows, not by seconds on a particular computer.

Algorithms whose steps grow like a polynomial, such as n, n², or n³, are said to run in reasonable time. Linear search (about n steps), binary search (about log n), and simple sorting methods (about n²) are all reasonable.

Algorithms whose steps grow exponentially, like 2n, or faster, like n! (factorial), run in unreasonable time. They might be fine for tiny inputs and hopeless for slightly bigger ones. Trying every possible subset of 60 items means 260 combinations, over a billion billion, which would take even a very fast computer decades or longer.

A famous example is the traveling salesperson problem: find the shortest route that visits every city once and returns home. Checking every possible route works for 5 cities (a few dozen routes) but explodes with 30 cities.

When an exact solution takes unreasonable time, programmers use a heuristic: a shortcut that finds a good, but not guaranteed best, solution quickly. "Always go to the nearest unvisited city next" is a heuristic for the traveling salesperson. Navigation apps, scheduling tools and game AI rely on heuristics every day.

Step 5 of 10Compare

How fast step counts grow

Aspectn = 10n = 20n = 30n = 60
log₂ n (binary search)about 3about 4about 5about 6
n (linear search)10203060
n² (simple sorting)1004009003,600
2ⁿ (every subset)1,024about 1 millionabout 1 billionabout 1 billion billion
VerdictAll fineAll fine2ⁿ getting slow2ⁿ hopeless

Step 6 of 10Practice · Sort into groups

Does each running time count as reasonable or unreasonable?

Tap an item, then tap its group (or drag it there).

Step 7 of 10Learn

Problems no algorithm can solve

Some problems aren't just slow; they're impossible to solve with an algorithm in general.

A decision problem has a yes-or-no answer, such as "Is this number prime?" A decision problem is decidable if some algorithm can give a correct answer for every possible input. Checking whether a number is prime is decidable.

A problem is undecidable if no algorithm can be written that always answers correctly for every input. The most famous example is the halting problem, studied by the mathematician Alan Turing in 1936: given any program and its input, decide whether the program will eventually stop or run forever. Turing proved that no algorithm can do this correctly for all programs.

Undecidable doesn't mean the problem can never be answered for any case. For many specific programs you can easily tell whether they halt. It means no single algorithm works for all cases.

This is a surprising and important limit. Computers are extraordinarily powerful, but there are well-defined questions they provably cannot always answer. Knowing the difference between "slow," "needs a heuristic" and "impossible in general" is part of thinking like a computer scientist.

From fast to impossibleReasonable timeNo algorithm works for every inputlog n: binarysearchn, n²: polynomial2ⁿ, n!:unreasonableHeuristic: goodenough, fastUndecidable:halting problem

Step 8 of 10Note

Step 9 of 10Practice · Code challenge

Write binaryChecks(list, target) that performs a binary search on a sorted list of numbers and returns how many elements it compared before finding the target, or before giving up if the target isn't in the list. Check the middle element with Math.floor((low + high) / 2) each time.

Runs in a sandbox in your browser.
  • binaryChecks([1, 3, 5, 7, 9, 11, 13], 7)
  • binaryChecks([1, 3, 5, 7, 9, 11, 13], 13)
  • binaryChecks([1, 3, 5, 7, 9, 11, 13], 4)
  • binaryChecks([2, 4], 4)

Step 10 of 10Practice · Choose one

A delivery company needs good routes for 200 stops every morning. Checking every possible route would take years. What is the most reasonable approach?