Back

Activity 2.12: Efficiency, Heuristics, and Undecidability

divider

Activity 2.12

Efficiency, Heuristics, and Undecidability

Key Concepts

Counting Steps as the Input Grows

Reasonable and Unreasonable Time

Heuristics: Good Enough, Fast

Problems No Algorithm Can Solve

Binary Search Left a Bill on the Table

Activity 2.10's binary search was dramatically faster than linear search, with one condition: the array had to be sorted.

Somebody has to do the sorting, and it is not free. Today puts a number on what sorting costs — and then uses that number to compare every algorithm you have met this unit.

Many Ways to Sort, One Finished Order

There are dozens of sorting algorithms. Fed the same array, they all finish with the same order, and they take completely different routes to it — with different amounts of work. In class you will watch three of them run side by side.

No sorting algorithm is on the AP exam. The one you build today is here because counting its steps is: the exam asks you to compare algorithms by how much work they do.

Selection Sort Picks the Smallest, Again and Again

The idea fits in one sentence: find the smallest element, swap it to the front, and repeat on everything after it. Each pass fixes one more position for good.

Value Trace
{ 42, 17, 93, 8, 55, 31 }
Look at everything. The smallest is 8.
Swap it with the first element, 42.
{ 8, 17, 93, 42, 55, 31 }
^ done. Never look at it again.
Now do the same to everything after it.

Selection Sort Picks the Smallest, Again and Again

Finding the smallest is Activity 2.9's Algorithm A, run on the part of the array starting at i.

Demo
int smallest = i;
for (int j = i + 1; j < list.Length; j++)
{
if (list[j] < list[smallest])
{
smallest = j;
}
}

It remembers the index, not the value. To swap the smallest into place, you need to know where it was.

A Swap Needs Three Lines

Swapping two elements looks like two assignments: copy the second into the first, then the first into the second. Predict what this prints.

Demo
int[] list = { 8, 3 };
list[0] = list[1];
list[1] = list[0];
Console.WriteLine($"{list[0]} {list[1]}");
Demo
3 3

A Swap Needs Three Lines

3 and 3. The first assignment overwrote the 8 before the second one could copy it. A third variable holds the 8 for exactly one line.

Demo
int[] list = { 8, 3 };
int temp = list[0];
list[0] = list[1];
list[1] = temp;
Console.WriteLine($"{list[0]} {list[1]}");
Demo
3 8

Count Steps, Not Seconds

For three sessions you have counted checks and comparisons, not timed anything. That is deliberate.

A fast computer makes a slow algorithm look fine on small input. The College Board defines efficiency as an estimate of the computational resources an algorithm uses, “typically expressed as a function of the size of the input” — how the step count grows as the input grows.

Every Algorithm From This Unit, Side by Side

Binary search, linear search, and selection sort, counted on arrays of 8, 16, 32 and a million elements. Each number is the worst-case step count. Predict the bottom row first.

Every Algorithm From This Unit, Side by Side

Value Trace
n binary linear sort
8 4 8 28
16 5 16 120
32 6 32 496
1000000 20 1000000 499999500000

A million elements: binary search needs 20 steps, and selection sort nearly 500 billion.

The Shape Matters More Than the Numbers

Value Trace
Double the list, and the work...
binary search goes up by one step
linear search doubles
selection sort goes up about four times

Each shape comes from the code. Halving each pass gives one more step per doubling. One loop over the array grows with its size. A loop inside a loop, like the sort, grows with the size multiplied by itself.

Then There Is Doubling

Some algorithms double their work every time the input grows by just one. Predict how long the n = 64 row takes at a billion steps a second.

Value Trace
n doubling: 2 multiplied by itself n times
8 256
16 65536
32 4294967296
64 18446744073709551616

Then There Is Doubling

About 585 years. Not because the computer is slow: because each extra item doubles the work, the input only has to grow a little for the time to become impossible.

Reasonable Time and Unreasonable Time

Reasonable time is polynomial efficiency or lower: constant, halving, linear, square, cube. Binary search, linear search and selection sort all qualify.

Unreasonable time is exponential (doubling) or factorial efficiency.

Cube on a million items is a very long time and is still called reasonable. The line is about whether better hardware can ever rescue you: a machine 1000 times faster solves a much bigger reasonable problem, but handles about ten more items of a doubling one.

Two Words Before We Start

A problem is a general description of a task. An instance of it includes specific input.

The College Board's own example: sorting is a problem; sorting the list (2, 3, 1, 7) is an instance of it. Keep both words — the end of the session needs them.

Some Problems Ask Yes or No; Some Ask for the Best

A decision problem has a yes-or-no answer: is there a delivery route under 30 blocks?

An optimization problem looks for the best solution among many: what is the shortest delivery route?

The Shortest Route Means Trying Every Order

A delivery van has to visit every stop and return to the depot. The sure way to find the shortest route is to try every order the stops could come in and keep the best.

Predict how many orders there are for 20 stops.

The Shortest Route Means Trying Every Order

Value Trace
stops orders to try
5 120
10 3628800
15 1307674368000
20 2432902008176640000

Each new stop multiplies the count by the new number of stops. That is factorial growth — unreasonable time. At a million orders a second, twenty stops takes about 77,000 years.

So Stop Insisting on the Best

A heuristic is an approach that produces a solution not guaranteed to be optimal, used when a technique that always finds the optimal one is impractical.

Impractical, not impossible. The best route exists; nobody can wait 77,000 years for it. A heuristic trades the guarantee for an answer you can actually get.

A Very Simple Rule

Always drive to the nearest stop you have not visited yet. Five stops means five decisions, not 120 orders to try. Predict whether it finds a good route.

A Very Simple Rule

Value Trace
Depot -> Chen 2 blocks
Chen -> Alvarez 6 blocks
Alvarez -> Boyd 4 blocks
Boyd -> Emeka 4 blocks
Emeka -> Diaz 12 blocks the only stop left
Diaz -> Depot 8 blocks the trip home
Total: 36 blocks
Value Trace
Best possible route: 24 blocks
The nearest-stop rule: 36 blocks
Half as long again, found instantly.

Every Step Was Nearest, and the Route Was Not

Each step took the closest option available, and it still stranded Diaz out at the far edge, to be fetched on a long trip at the very end.

That is what a heuristic is: sensible at every step, with no guarantee about the whole. Routing apps, seating charts and packing delivery trucks all run on heuristics. Which specific heuristic is not exam content; the idea is.

A Decidable Problem Can Always Be Answered

A decidable problem is a decision problem for which an algorithm can be written that gives a correct output for all inputs. The College Board's example: is the number even?

Almost everything you have written this year is one. Is the ghost in this house? Is 67 in this array? Always answerable.

Write Me This Method

Given any program, decide whether it eventually finishes or runs forever. Yes or no — another decision problem, and one every programmer would love to have.

Demo
bool WillItStop(string program)
{
// true if the program eventually finishes
// false if it runs forever
}

Write Me This Method

It cannot be written. Not “nobody has managed yet”: Alan Turing proved in 1936 that no such method can exist. This is the halting problem.

An undecidable problem is one for which no algorithm can be constructed that is always capable of giving a correct yes-or-no answer. Not slow. Not unsolved. Impossible.

Read the Word Always Carefully

An undecidable problem can still have instances you can solve. Some programs obviously finish; some obviously loop forever, like Activity 1.17's.

What cannot exist is one algorithm that handles every instance. That is the difference the word instance was saved for.

Three Walls, and Only One Has a Workaround

Reasonable time: write the algorithm.

Unreasonable time: solvable, but not at real sizes. A heuristic gives a good-enough answer.

Undecidable: no algorithm exists for all instances, and a heuristic does nothing for it. Do not merge the last two— the exam checks whether you can tell them apart.

Today's Objectives

  • Counting the steps an algorithm takes as its input grows
  • Telling reasonable time from unreasonable time
  • Using a heuristic when the best answer is out of reach, and judging it
  • Explaining what makes a problem undecidable

Key Terms

Efficiency
An estimate of the computational resources an algorithm uses, as a function of the size of its input.
Reasonable time
Polynomial efficiency or lower: constant, halving, linear, square, cube.
Unreasonable time
Exponential or factorial efficiency.

Key Terms, Continued

Problem and instance
A general task, and that task with specific input.
Decision and optimization problems
One has a yes-or-no answer; the other looks for the best solution among many.
Heuristic
An approach giving a solution not guaranteed to be optimal, used when finding the optimal one is impractical.
Undecidable problem
A problem for which no algorithm can always give a correct yes-or-no answer.

'F' → Fullscreen

divider

Build

Two short programs today. First the go-kart race is over, in a new program named 2-12-race-results: the results board is in the order people crossed the timing mat, not the order they finished. You sort it, then find out how much work sorting a bigger race would take. Then you plan a route around a theme park, where the best answer is out of reach and a heuristic has to do.

How to read the code blocks. Each task's code block shows your whole program, from line 1, as it should look when that task is finished.

The green lines marked with a + are the ones you add or change for that task — everything else is already in your file. Do not type the + sign.


Task 1: Sort the Results

  • Two parallel arrays: racers and their lap times in seconds. SortByTime is selection sort on the times, and it counts every comparison. Its bool parameter decides whether it prints the times after each pass.
  • Every swap of a time swaps the matching racer too, so names stay with their times. That is why there are two swaps.
  • Write the code below and run it. One of the five passes changes nothing. Find it, and say why the array did not move.
  • Now delete the three lines that swap the racers' names and run it. Record who it says won, and say why there was no error. Put the lines back.
2-12-race-results
string[] racers = { "Zippy", "Blaze", "Comet", "Rocket", "Nova", "Turbo" };
int[] times = { 94, 87, 102, 79, 91, 85 };
int comparisons = SortByTime(true);
Console.WriteLine($"Comparisons: {comparisons}");
Console.WriteLine($"Winner: {racers[0]} in {times[0]} seconds");
int SortByTime(bool show)
{
int comparisons = 0;
for (int i = 0; i < times.Length - 1; i++)
{
int fastest = i;
for (int j = i + 1; j < times.Length; j++)
{
comparisons = comparisons + 1;
if (times[j] < times[fastest])
{
fastest = j;
}
}
int tempTime = times[i];
times[i] = times[fastest];
times[fastest] = tempTime;
string tempName = racers[i];
racers[i] = racers[fastest];
racers[fastest] = tempName;
if (show)
{
Console.Write($"After pass {i + 1}:");
for (int k = 0; k < times.Length; k++)
{
Console.Write($" {times[k]}");
}
Console.WriteLine();
}
}
return comparisons;
}

Task 2: Sort It Again, Then Bigger Races

  • Lines 8–9 sort the results a second time, now that they are already in order. Before you run it, predict that comparison count. Linear search got faster when it got lucky; say why this sort does not.
  • The new loop builds races of 8, 16, 32 and 64 racers with random times between 60 and 180 seconds, and sorts each one with show set to false. It works because SortByTime reads times and racers from the main program, and lines 15 and 16 point those names at new, bigger arrays (Activity 2.5: a method sees outward).
  • Run it and record the four counts. Each race is twice as big as the one before. Roughly how many times more comparisons does each one need? Compare with the deck's table.
2-12-race-results
string[] racers = { "Zippy", "Blaze", "Comet", "Rocket", "Nova", "Turbo" };
int[] times = { 94, 87, 102, 79, 91, 85 };
int comparisons = SortByTime(true);
Console.WriteLine($"Comparisons: {comparisons}");
Console.WriteLine($"Winner: {racers[0]} in {times[0]} seconds");
Console.WriteLine("Sorting the sorted results again:");
Console.WriteLine($"Comparisons: {SortByTime(true)}");
int[] sizes = { 8, 16, 32, 64 };
for (int s = 0; s < sizes.Length; s++)
{
times = new int[sizes[s]];
racers = new string[sizes[s]];
for (int k = 0; k < times.Length; k++)
{
times[k] = Random.Shared.Next(60, 181);
racers[k] = $"Racer {k + 1}";
}
Console.WriteLine($"{sizes[s]} racers: {SortByTime(false)} comparisons");
}
int SortByTime(bool show)
{
int comparisons = 0;
for (int i = 0; i < times.Length - 1; i++)
{
int fastest = i;
for (int j = i + 1; j < times.Length; j++)
{
comparisons = comparisons + 1;
if (times[j] < times[fastest])
{
fastest = j;
}
}
int tempTime = times[i];
times[i] = times[fastest];
times[fastest] = tempTime;
string tempName = racers[i];
racers[i] = racers[fastest];
racers[fastest] = tempName;
if (show)
{
Console.Write($"After pass {i + 1}:");
for (int k = 0; k < times.Length; k++)
{
Console.Write($" {times[k]}");
}
Console.WriteLine();
}
}
return comparisons;
}

Task 3: Put a Time on It

  • A computer does about a billion steps a second. Work out roughly how long each of these takes, and write down your arithmetic:
    1. Linear search through a billion records
    2. Binary search through a billion sorted records
    3. Selection sort on a million records
    4. A doubling algorithm on an input of 64
    One of these four does not finish in your lifetime. Say which.
  • Add Doubling and the four lines that print it. Doubling returns a long: a whole number like int, but stored in 64 bits instead of 32, so it holds numbers about four billion times bigger. Compare Doubling(64) with the deck's table. It is not even close. Record all four results and explain what happened, using what Activity 1.2 showed about a fixed number of bits.
2-12-race-results
string[] racers = { "Zippy", "Blaze", "Comet", "Rocket", "Nova", "Turbo" };
int[] times = { 94, 87, 102, 79, 91, 85 };
int comparisons = SortByTime(true);
Console.WriteLine($"Comparisons: {comparisons}");
Console.WriteLine($"Winner: {racers[0]} in {times[0]} seconds");
Console.WriteLine("Sorting the sorted results again:");
Console.WriteLine($"Comparisons: {SortByTime(true)}");
int[] sizes = { 8, 16, 32, 64 };
for (int s = 0; s < sizes.Length; s++)
{
times = new int[sizes[s]];
racers = new string[sizes[s]];
for (int k = 0; k < times.Length; k++)
{
times[k] = Random.Shared.Next(60, 181);
racers[k] = $"Racer {k + 1}";
}
Console.WriteLine($"{sizes[s]} racers: {SortByTime(false)} comparisons");
}
Console.WriteLine($"Doubling(32): {Doubling(32)}");
Console.WriteLine($"Doubling(62): {Doubling(62)}");
Console.WriteLine($"Doubling(63): {Doubling(63)}");
Console.WriteLine($"Doubling(64): {Doubling(64)}");
int SortByTime(bool show)
{
int comparisons = 0;
for (int i = 0; i < times.Length - 1; i++)
{
int fastest = i;
for (int j = i + 1; j < times.Length; j++)
{
comparisons = comparisons + 1;
if (times[j] < times[fastest])
{
fastest = j;
}
}
int tempTime = times[i];
times[i] = times[fastest];
times[fastest] = tempTime;
string tempName = racers[i];
racers[i] = racers[fastest];
racers[fastest] = tempName;
if (show)
{
Console.Write($"After pass {i + 1}:");
for (int k = 0; k < times.Length; k++)
{
Console.Write($" {times[k]}");
}
Console.WriteLine();
}
}
return comparisons;
}
long Doubling(int n)
{
long total = 1;
for (int i = 0; i < n; i++)
{
total = total * 2;
}
return total;
}

Task 4: Nearest Ride Next

  • You have one afternoon at a theme park, in a second program named 2-12-theme-park. Six rides, a gate you enter and leave by, and paths on a grid. You want to ride everything and walk as little as possible, and the deck showed why trying every order is hopeless.
  • The park is three parallel arrays: ride names and grid positions. Steps counts the steps between two places along the paths, across plus up or down, never diagonally. NearestRoute always walks to the nearest ride it has not ridden yet, using a bool array the way Raylib Lab 6 remembered which invaders were hit.
  • Run it, then answer three questions. (a) The best possible route for this park is 36 steps. Find the leg of yours that cost the most, and explain why the rule walked into it. (b) Write a different rule for choosing the next ride. It does not have to be better; it has to be a rule a computer could follow. (c) Could you check every order by hand for six rides? For twenty? What changed?
2-12-theme-park
string[] rides = { "Gate", "Carousel", "Ferris Wheel", "Coaster", "Log Flume", "Bumper Cars", "Haunted Mine" };
int[] xs = { 0, 0, 0, 3, 7, 4, 9 };
int[] ys = { 0, 4, 7, 0, 2, 7, 9 };
NearestRoute();
int Steps(int a, int b)
{
int dx = xs[a] - xs[b];
int dy = ys[a] - ys[b];
if (dx < 0)
{
dx = -dx;
}
if (dy < 0)
{
dy = -dy;
}
return dx + dy;
}
int NearestRoute()
{
bool[] visited = new bool[rides.Length];
visited[0] = true;
int current = 0;
int total = 0;
for (int stop = 1; stop < rides.Length; stop++)
{
int best = -1;
for (int i = 0; i < rides.Length; i++)
{
if (!visited[i] && (best == -1 || Steps(current, i) < Steps(current, best)))
{
best = i;
}
}
Console.WriteLine($" to the {rides[best]}: {Steps(current, best)} steps");
total = total + Steps(current, best);
visited[best] = true;
current = best;
}
Console.WriteLine($" back to the Gate: {Steps(current, 0)} steps");
total = total + Steps(current, 0);
Console.WriteLine($"Total: {total} steps");
return total;
}

Challenge (Optional): Try Every Starting Point

  • Give NearestRoute a parameter for the ride it starts from, and run the rule from all seven places. Print each total and the best.
  • The best of the seven matches the best possible route. Is the program still using a heuristic? Explain.
divider

Same Idea, Exam Notation

C#
int temp = list[i];
list[i] = list[smallest];
list[smallest] = temp;
Exam Notation
temp ← aList[i]
aList[i] ← aList[smallest]
aList[smallest] ← temp

1. The Swap Lines Up Almost Exactly

Assigning one list element to another is written the same way in both notations, with ← in place of =. The exam expects you to read a three-line swap and know why it needs the third variable.

2. Copying a List Does Not Mean the Same Thing

On the reference sheet, aList ← bList assigns a copy of the list. In C#, int[] a = b; makes a second name for the same array — Activity 1.23's copy pair. Sort through one name, and the other sees the change.

So an exam question can hand you two list names, sort one, and expect the other to be untouched. The same question in C# would have a different answer.

3. Counting the Steps in a Nested Loop

Exam Notation
i ← 1
REPEAT UNTIL(i > n)
{
j ← 1
REPEAT UNTIL(j > n)
{
<one step>
j ← j + 1
}
i ← i + 1
}

The question is almost always the same: how many times does the inner statement run? Read the bounds, not the shape. Two loops that each run n times give n × n steps. If the inner loop ran 3 times instead, it would be 3 × n, which grows like n, not like n × n.

And one thing you will not be asked for. There is a formal notation for efficiency, and the course framework puts it outside the exam. Twice the input, four times the work is the level of answer the exam wants.

divider

Checkpoint

Task 1 prints exactly this.

Task 1
After pass 1: 79 87 102 94 91 85
After pass 2: 79 85 102 94 91 87
After pass 3: 79 85 87 94 91 102
After pass 4: 79 85 87 91 94 102
After pass 5: 79 85 87 91 94 102
Comparisons: 15
Winner: Rocket in 79 seconds

And Task 4 prints exactly this.

Task 4
to the Coaster: 3 steps
to the Log Flume: 6 steps
to the Bumper Cars: 8 steps
to the Ferris Wheel: 4 steps
to the Carousel: 3 steps
to the Haunted Mine: 14 steps
back to the Gate: 18 steps
Total: 56 steps

56 is the right answer for this heuristic. It is also the wrong answer for the problem, and knowing the difference is the point.

  • Rocket wins in 79 seconds, and you recorded the pass that changed nothing and the wrong winner with the name swap removed
  • You recorded the sorted-again count and the four race-size counts, with how they grow
  • You estimated all four Task 3 times, and explained what Doubling(64) printed
  • You answered Task 4's three questions
divider

Reflection

Answer the following questions before submitting your work.

  1. Sorting six racers took 15 comparisons, and binary search on six takes about three. When is it worth paying the 15?
  2. The rule chose the nearest ride every time and finished more than half as long again as the best route. Explain how both can be true at once.
  3. A slow problem and an undecidable problem both leave you without an answer. Why is it still worth having two different words for them? Use the word instance in your answer.
divider

Submit

Submit four things to the dropbox:

  1. Your 2-12-race-results and 2-12-theme-park program files.
  2. The pass that changed nothing, the wrong winner, your sorted-again prediction and count, and your four race-size counts.
  3. Your four Task 3 estimates, what Doubling printed with your explanation, and your Task 4 answers.
  4. Your three reflection answers.

Activity Complete