Town 04 · Algorithms

The guild

Eight residents who each know one method by heart: ways to search, to sort, to look something up, to find a route and to plan. Each method works the same whether there are ten things or ten million.

Search · O(log n)

The guesser

Ask her to find a name in a sorted list and she never starts at the top. She opens it in the middle, sees which half the name is in, and throws the other half away. Seven guesses cover a hundred names, and twenty cover a million.

The ideaHalve what is left, every time

4321

Recursion · a function that calls itself

The doll maker

To open a doll, he opens the doll inside it, and that one opens the doll inside it, until he reaches one so small it does not open at all. Then the answers come back out, one doll at a time, in reverse.

The ideaSolve a smaller copy, until it is trivial

Sort · O(n log n)

The foreman

She picks one plank as the pivot. Everything shorter goes to its left, everything taller to its right, then she hands each pile to a helper who does exactly the same. A pile of one plank is already sorted.

The ideaSplit around a pivot, then repeat

01234567891011h(key)

Lookup · O(1) on average

The cashier

Ask her the price of anything and she answers at once. She never searches the shelves: the name of the thing tells her which cubby it is in, so the thousandth item takes no longer than the first.

The ideaThe key says where to look

Breadth-first search · nearest first

The town crier

He asks his friends first, then their friends, then theirs, and never skips ahead a ring. So the first person he finds who can help is also the closest one, and he only ever knocks on each door once.

The ideaSearch outwards, ring by ring

623150526

Shortest path · weighted roads

The navigator

The route with the fewest turns is not always the quickest. She keeps a running total for every crossing, always walks on from the cheapest one she has not finished, and never has to go back to it.

The ideaAlways extend the cheapest route

41¢25105125+10+5+1

Greedy · the best move right now

The shopkeeper

He makes change with the biggest coin that fits, then the biggest that fits what is left, and never thinks twice. For coins that is exactly right. For packing a bag it can be quite wrong, but when nothing faster exists, close is often good enough.

The ideaTake the best step, never look back

Planning · one square at a time

The quilter

She never takes on the big problem in one go. She works through a grid one square at a time, building each square from ones she has already finished, so nothing is ever worked out twice. The last square holds the answer.

The ideaSmall answers, saved and reused