Back

Activity 2.9: Algorithms and Linear Search

divider

Activity 2.9

Algorithms and Linear Search

Key Concepts

What an Algorithm Is

Many Algorithms, One Problem

Linear Search

Best Case and Worst Case

Part 1 Asked Whether Your Code Worked

Every program in Part 1 was judged one way: does it give the right answer? Build 1 passed or failed on its requirements, and none of them asked how much work the program did to get there.

Part 3 asks the second question. Two programs can give exactly the same answer while one of them does several times the work. On five numbers nobody notices. On five million, that difference decides whether a program is usable.

You Have Been Writing Algorithms All Year

An algorithm is a finite set of instructions that accomplishes a task. Finite means it ends: Activity 1.17's loop that never stopped was a set of instructions, but not an algorithm.

Every method you have written with a loop that reaches its end was one. Today's question is not whether something is an algorithm, but how to compare two of them.

Same Problem, Two Algorithms

The problem: find the largest number in an array. Here is the array both answers will use.

Demo
int[] scores = { 12, 40, 91, 7, 63 };

Algorithm A remembers the best so far and looks at each number once — Activity 1.20's running maximum.

Same Problem, Two Algorithms

Demo
int LargestA()
{
int best = scores[0];
for (int i = 1; i < scores.Length; i++)
{
if (scores[i] > best)
{
best = scores[i];
}
}
return best;
}

Same Problem, Two Algorithms

Algorithm B takes each number in turn and checks whether it beats every number in the array. The first one that does is the answer. Its body, on the next slide, is a loop inside a loop.

Same Problem, Two Algorithms

Demo
for (int i = 0; i < scores.Length; i++)
{
bool beatsEveryone = true;
for (int j = 0; j < scores.Length; j++)
{
if (scores[j] > scores[i])
{
beatsEveryone = false;
}
}
if (beatsEveryone)
{
return scores[i];
}
}

Same Answer, Different Work

Both return 91. Both are correct. Predict how many comparisons each one makes — how many times an if compares two numbers.

Value Trace
scores = { 12, 40, 91, 7, 63 }
LargestA looks at 40, 91, 7, 63 once each 4 comparisons
LargestB 12 against all five -> beaten
40 against all five -> beaten
91 against all five -> wins 15 comparisons

Same Answer, Different Work

4 against 15, on five numbers, for the same answer. And B got lucky: the largest number was third. Had it been last, B would have made 25 comparisons.

Correctness is not the only thing worth measuring. That gap is the whole of Part 3, and Activity 2.12 puts real numbers on it.

Check Each One in Order

The search everyone invents first: start at the beginning, check each element, and stop when you find it. It is called linear search, or sequential search — two names for one algorithm, and the exam uses both.

Demo
string[] crew = { "Vega", "Orion", "Lyra", "Draco", "Cygnus" };
Console.WriteLine(Find("Lyra"));
Console.WriteLine(Find("Rigel"));

Predict both outputs from the method on the next slide.

Check Each One in Order

Demo
int Find(string name)
{
for (int i = 0; i < crew.Length; i++)
{
if (crew[i] == name)
{
return i;
}
}
return -1;
}
Demo
2
-1

Check Each One in Order

Lyra is at index 2, and the return inside the loop stops the search the moment she is found — Activity 2.3's early return doing real work. Cygnus and Draco are never looked at.

Rigel is not in the array, so the loop runs to the end and the method reaches return -1.

-1 Means Not Here Because No Index Can Be -1

Every real index is 0 or bigger. So -1 cannot be mistaken for a place in the array, and the caller can test for it: if (Find(name) == -1).

Return 0 for not-found instead and the caller cannot tell “not here” from “first in the list.” A value chosen because it cannot be a real answer is called a sentinel, and you will meet the idea again.

Three Cases, and the Worst One Counts

Best case: the target is first. One check.

Worst case: the target is last, or not there at all. Every element is checked — five for crew, a million for a million names.

Algorithms are compared by their worst case, because that is the one a user eventually hits. “It is usually fast” is not a promise anyone can rely on.

Linear Search Never Fails, and That Costs Something

It works on any array: sorted or not, numbers or names. It makes no assumptions, so nothing can break them.

The price is the worst case: every element, every time. Activity 2.10 gives up the “any array” guarantee and gets something far faster in return.

Today's Objectives

  • Defining an algorithm as a finite set of instructions
  • Showing that one problem has many correct algorithms
  • Writing a linear search that reports where it found something
  • Counting the checks in the best, worst, and not-found cases

Key Terms

Algorithm
A finite set of instructions that accomplishes a task.
Linear search
Checking each element in order until the target is found or every element has been checked; also called sequential search.
Worst case
The input that makes an algorithm do the most work.
Sentinel
A value chosen because it can never be a real answer, such as -1 for not found.

'F' → Fullscreen

divider

Build

Tonight you search a haunted house, in a new program named 2-9-haunted-house. Eight rooms, each holding something — dust, cobwebs, bats, and one ghost. You open doors in order until you find what you are looking for, and every door you open is one check.

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: Find the Ghost

  • Two arrays line up by position: rooms names each room, and contents says what is in it. SearchHouse opens doors in order, counts them, and returns the room's index — or -1 if it never finds the target.
  • Before you run it, predict how many doors it opens. Then write the code below, run it, and compare.
2-9-haunted-house
string[] rooms = { "Hall", "Kitchen", "Library", "Parlor", "Cellar", "Nursery", "Study", "Tower" };
string[] contents = { "dust", "cobwebs", "dust", "ghost", "rats", "dust", "cobwebs", "bats" };
SearchHouse("ghost");
int SearchHouse(string target)
{
int doors = 0;
for (int i = 0; i < rooms.Length; i++)
{
doors = doors + 1;
Console.WriteLine($"Opening the {rooms[i]}... {contents[i]}");
if (contents[i] == target)
{
Console.WriteLine($"Found the {target} in the {rooms[i]}. Doors opened: {doors}.");
return i;
}
}
Console.WriteLine($"No {target} anywhere. Doors opened: {doors}.");
return -1;
}

Task 2: Three Cases

  • Replace the one search with the three on lines 4–6, and run it.
  • One of the three is the best case, one is the worst case, and one is not found. Label each one, with its door count.
  • Explain why searching for something that is not in the house costs exactly the same as searching for whatever is in the last room.
2-9-haunted-house
string[] rooms = { "Hall", "Kitchen", "Library", "Parlor", "Cellar", "Nursery", "Study", "Tower" };
string[] contents = { "dust", "cobwebs", "dust", "ghost", "rats", "dust", "cobwebs", "bats" };
SearchHouse("dust");
SearchHouse("bats");
SearchHouse("pirate");
int SearchHouse(string target)
{
int doors = 0;
for (int i = 0; i < rooms.Length; i++)
{
doors = doors + 1;
Console.WriteLine($"Opening the {rooms[i]}... {contents[i]}");
if (contents[i] == target)
{
Console.WriteLine($"Found the {target} in the {rooms[i]}. Doors opened: {doors}.");
return i;
}
}
Console.WriteLine($"No {target} anywhere. Doors opened: {doors}.");
return -1;
}

Task 3: The Ghost Moves Every Night

  • Put the single ghost search back, but now the ghost hides in a random room each time the program runs. The Parlor gets candles instead, and lines 4–5 put the ghost in a random room with Activity 1.15's Next.
  • Run it ten times and record the door count each time.
  • Write down the fewest and most doors you saw, the fewest and most that are possible, and the average of your ten. How close is the average to halfway through the house?
2-9-haunted-house
string[] rooms = { "Hall", "Kitchen", "Library", "Parlor", "Cellar", "Nursery", "Study", "Tower" };
string[] contents = { "dust", "cobwebs", "dust", "candles", "rats", "dust", "cobwebs", "bats" };
int hiding = Random.Shared.Next(0, rooms.Length);
contents[hiding] = "ghost";
SearchHouse("ghost");
int SearchHouse(string target)
{
int doors = 0;
for (int i = 0; i < rooms.Length; i++)
{
doors = doors + 1;
Console.WriteLine($"Opening the {rooms[i]}... {contents[i]}");
if (contents[i] == target)
{
Console.WriteLine($"Found the {target} in the {rooms[i]}. Doors opened: {doors}.");
return i;
}
}
Console.WriteLine($"No {target} anywhere. Doors opened: {doors}.");
return -1;
}

Task 4: A Search That Cannot Stop Early

  • Replace the comments at the bottom with CountInHouse, written yourself. It returns how many rooms hold the target. Line 8 calls it for dust.
  • SearchHouse stops at the first match. Explain why CountInHouse cannot, and what that does to its best case.
  • Run it several times. Every so often, the dust count drops from 3 to 2. Work out why, and say which line causes it.
2-9-haunted-house
string[] rooms = { "Hall", "Kitchen", "Library", "Parlor", "Cellar", "Nursery", "Study", "Tower" };
string[] contents = { "dust", "cobwebs", "dust", "candles", "rats", "dust", "cobwebs", "bats" };
int hiding = Random.Shared.Next(0, rooms.Length);
contents[hiding] = "ghost";
SearchHouse("ghost");
Console.WriteLine($"Rooms with dust: {CountInHouse("dust")}");
int SearchHouse(string target)
{
int doors = 0;
for (int i = 0; i < rooms.Length; i++)
{
doors = doors + 1;
Console.WriteLine($"Opening the {rooms[i]}... {contents[i]}");
if (contents[i] == target)
{
Console.WriteLine($"Found the {target} in the {rooms[i]}. Doors opened: {doors}.");
return i;
}
}
Console.WriteLine($"No {target} anywhere. Doors opened: {doors}.");
return -1;
}
// CountInHouse(target) returns how many rooms hold target.
// Check every room, and add 1 to a counter each time the
// room's contents match. Return the counter at the end.
// Write it here, below SearchHouse.

Challenge (Optional): Start From the Tower

  • Write SearchFromTop, which opens the doors in the opposite order: Tower first, Hall last. A for loop can count down as well as up.
  • Search for the same things as Task 2. Which searches got faster, which got slower, and is the worst case any better?
divider

Same Idea, Exam Notation

The deck's Find, written the way the AP exam would write it.

C#
int Find(string name)
{
for (int i = 0; i < crew.Length; i++)
{
if (crew[i] == name)
{
return i;
}
}
return -1;
}
Exam Notation
PROCEDURE find(aList, name)
{
i ← 1
REPEAT UNTIL(i > LENGTH(aList))
{
IF(aList[i] = name)
{
RETURN(i)
}
i ← i + 1
}
RETURN(-1)
}

1. There Is No for Loop

The reference sheet has no for. You keep the counter yourself: set i before the loop and add 1 to it at the bottom of the loop's body. Forgetting the i ← i + 1 makes a loop that never ends, exactly as a while without its update did in Activity 1.17.

2. REPEAT UNTIL Is the Opposite of while

C# repeats while there is more array to check. The exam repeats until it has gone past the end, so the condition is flipped: i > LENGTH(aList).

3. Exam Lists Start at 1

This is the one that costs points. Lyra is at index 2 in C# and index 3 on the exam. Both are correct in their own notation. Before you answer a question about a position, check which notation you are reading.

divider

Checkpoint

Task 2 prints exactly this.

Example Output
Opening the Hall... dust
Found the dust in the Hall. Doors opened: 1.
Opening the Hall... dust
Opening the Kitchen... cobwebs
Opening the Library... dust
Opening the Parlor... ghost
Opening the Cellar... rats
Opening the Nursery... dust
Opening the Study... cobwebs
Opening the Tower... bats
Found the bats in the Tower. Doors opened: 8.
Opening the Hall... dust
Opening the Kitchen... cobwebs
Opening the Library... dust
Opening the Parlor... ghost
Opening the Cellar... rats
Opening the Nursery... dust
Opening the Study... cobwebs
Opening the Tower... bats
No pirate anywhere. Doors opened: 8.
  • SearchHouse returns the index it found, or -1, and counts every door it opens
  • You labeled the best case, the worst case, and not found, with their door counts
  • You recorded ten random searches, with the fewest, most, and average
  • CountInHouse returns 3 for dust unless the ghost lands in a dusty room, and you explained why it is then 2
divider

Reflection

Answer the following questions before submitting your work.

  1. Algorithm B on the deck is correct and does almost four times the work of Algorithm A. Is it a bad algorithm? Defend your answer.
  2. Linear search works on any array, sorted or not. Name the price you pay for that guarantee, using your door counts.
  3. SearchHouse returns -1 for not found. What would go wrong if it returned 0 instead?
divider

Submit

Submit four things to the dropbox:

  1. Your 2-9-haunted-house program file, with your CountInHouse.
  2. Your Task 1 prediction, and the Task 2 labels with their door counts and your not-found explanation.
  3. Your ten Task 3 door counts with the fewest, most, and average, and your Task 4 answers about stopping early and the dust count.
  4. Your three reflection answers.

Activity Complete