Overview
This lesson is linear (sequential) search, the one learning objective of the topic (4.14.A): write code that searches a collection for a target and determine what a search returns. Day 1 is the standard search on an int array: check each element in order, return the index the moment it matches, and return -1 only after the loop has checked everything (4.14.A.1). Day 2 is stopping: a while loop whose condition does the searching, short-circuit evaluation guarding the array access, and counting the comparisons a search makes in the best and worst cases. Day 3 carries the search to an ArrayList of strings (size(), get(i), equals), runs it from the last element toward the first (4.14.A.1, “from either end”), and searches a 2D array by taking each row and running a linear search on it (4.14.A.2).
Students already have every piece: indexed traversals of arrays, ArrayLists, and 2D arrays (Topics 4.4, 4.9, 4.12), the “at least one element has a property” algorithm (4.5), return leaving a method from inside a loop (3.5), equals versus == (2.6), short-circuit && (2.5), and counting statement executions with a counter (2.12). Say so often: today’s algorithm is a traversal that is allowed to stop early.
Stay inside the topic boundary. Binary search, sorting, and recursion are Topics 4.15–4.17: do not mention that a sorted list could be searched faster, even when a student asks why a search must check every element. The answer for this topic is that an unordered list gives no hint where the target is. Do not use indexOf or contains on an ArrayList as a shortcut; the point is to write the search. String’s indexOf (Topic 1.15) appears only as an earlier example of -1 meaning “not found.”
Teacher note
The slides are the Hide and Seek deck (21 slides, with speaker notes); slide numbers below refer to it. Day 1 uses slides 1–7, Day 2 uses slides 8–14, and Day 3 uses slides 15–21. The Hide and Seek puzzle worksheet (9 questions, about 30 minutes) is spread over all three days: questions 1 and 8 in class and question 7 as homework after Day 1; question 3 as homework after Day 2; question 2 in class and questions 4, 5, 6, and 9 as homework after Day 3. Question 6, version 2, searches from the end, so hold question 6 until after Day 3.
All files are in the topic’s examples/ folder. Running them is optional; the slides carry the examples. Files ending in .snippet.java hold only the statements that go inside main.
- Day 1 demonstrations:
LinearSearchBasic,EarlyReturnBug,FirstMatch,NegativeIndexCrash. - Day 2 demonstrations:
WhileSearch,WhileMissing,WhileOrderBug,KeepLookingBug,CountComparisons,CounterPlacementBug,CountGrowth. - Day 3 demonstrations:
SearchNames,EqualsBug,HasName,SearchBackward,LatestVisit,BackwardStartBug,SearchGrid,SeatChart,GridReturnBug. - Printed only (exit ticket):
ExitLaps,ExitSeat,ExitFindCode.
Day 1 · Warm-up: Find the locker
Show slide 2: five names and locker numbers in no particular order. Partners answer the three questions in two minutes, then share. Steer the answers toward the three rules of the lesson: start at one end (the top), stop as soon as you see Rosa, and say “Rosa isn’t on the list” only after reading every name. Ask the follow-up: “If Rosa were the last name, how many names would you read? If she weren’t on the list at all?” (Five both times.) Name what they just did: a linear search for a target.
Day 1 · Direct instruction: Linear search returns an index
- Goals (slide 3). Goal 1 is today, goals 2 and 4 are Day 2 (with goal 3 split across both), and goal 5 is Day 3.
- The algorithm (slides 4–5; 4.14.A.1). Read
findIndexon slide 5 line by line. Three things to point at: the loop visits indexes0tovalues.length - 1; theifcompares one element with the target; and there are tworeturnstatements, one inside the loop and one after it. Cover the output and tracefindIndex(jerseys, 11)on the board: 23 no, 7 no, 11 yes,return 2;. Remind students thatreturnleaves the method right away, even from inside a loop (Topic 3.5), so indexes 3 and 4 are never looked at. ThenfindIndex(jerseys, 99): every comparison is false, the loop ends, and the method returns-1. RunLinearSearchBasicif the IDE is ready. - It returns where, not what. Ask: “We already know the value is 11. Why does the method return 2 and not 11?” A program needs the position to read a matching name from another list, to change the element, or to remove it. Worksheet question 1, choice C, is the student who returns the value.
- Why -1 (slide 6). Walk the table.
0andlength - 1are real indexes, so they cannot mean “not found”; no array has index-1. Name it a sentinel value. Students have seen it before:"hopper".indexOf("z")is-1(Topic 1.15). - Duplicates, briefly. Show
FirstMatch: 85 is at indexes 1 and 4, and the search returns 1. The search reports the first match it reaches. Day 2 returns to this.
Misconception: The search returns the value it found
Students write return values[i]; or pick the value in a trace, because “find 11” sounds like the answer is 11. Ask, every time, “What would the caller do with this number?” A caller that already knows the target needs its position. Worksheet question 1, choice C, and the exit ticket both check it.
Misconception: Return 0 when the target is missing
“Zero means nothing” feels natural. But 0 is the index of the first element, so a caller could not tell “found first” from “not found.” Slide 6’s table makes the case; worksheet question 1, choice D, and the snippet pool’s decoy 0 in question 5 test it.
Day 1 · Direct instruction: One mismatch does not prove it is missing
Show slide 7. The method adds an else { return -1; } beside the found case. Before revealing the output, ask students to predict findIndex(jerseys, 23) and findIndex(jerseys, 30). The first prints 0 (23 happens to be first); the second prints -1 even though 30 is at index 3. Trace the second call: i is 0, 23 is not 30, the else runs, and the method ends on its first pass. Whatever the target, this method only ever looks at one element.
Fix it with the slide’s rule: delete the else and keep the single return -1; after the loop. “Not found” can only be decided after the loop. Run EarlyReturnBug to show the same mistake with the guide’s scores array.
Misconception: If it does not match, say not found
“If it matches, say found; otherwise, say not found” sounds right in English, so students pair the two returns in an if/else. The bug hides when the test target is the first element. Teach students to test a search with a target that is not first. Worksheet question 8 (two truths and a lie) and question 4’s else decoy tile are built on this mistake.
Day 1 · Guided practice: Write findIndex and test five cases
Students close the slides, open the IDE, and write findIndex for an int array from memory, with a main that searches int[] bus = {14, 9, 22, 9, 31};. Before running, they write the expected result for each of five targets: the first element (14 → 0), a middle element (22 → 2), the last element (31 → 4), a duplicate (9 → 1), and a missing value (5 → -1). Then they run and compare.
Teacher note
The five cases are the point. A method with the else bug passes the first-element test and fails the others; a loop with i <= bus.length passes four tests and crashes only on the missing one. Circulate and ask anyone whose code “works” which of the five they have actually run. If computers are not available, students write the method on paper and trace the five calls as a class.
Day 1 independent practice and closure
Students work worksheet questions 1 and 8 in class (about seven minutes): you’re the JVM on findIndex with a duplicate and a missing target (answer A, 1 -1), and two truths and a lie about the else bug (claim 2 is the lie). Question 7 is homework: a one-token fix where i <= codes.length crashes only when the target is missing.
Misconception: Using -1 as an index
A search can hand back -1, and code like codes[find(codes, 5)] then asks for codes[-1], which throws an ArrayIndexOutOfBoundsException. Show NegativeIndexCrash. The rule: check if (spot != -1) before using the result as an index. The Watch Out after worksheet question 7 says the same.
For closure, ask: “When may a search return the index? When may it return -1?” (As soon as an element matches; only after every element has been checked.) Write both on the board and leave them up for Day 2.
Day 2 · Warm-up: Which 85?
Write int[] scores = {72, 85, 90, 64, 85}; and ask what findIndex(scores, 85) returns and why not 4 (1: the search stops at the first match it reaches). Then show KeepLookingBug, which records foundAt = i but never stops, and ask what it returns (4, the last match). Stopping is not only about speed: it decides which copy a search reports.
Misconception: Remembering the match is the same as stopping
Students store the index in a variable and let the loop run on, so a later copy overwrites it and the search reports the last match. Ask “Which line ends the search?” If no line does, it is not a first-match search. return i; inside the if is the fix; KeepLookingFixed shows a loop-condition fix (foundAt == -1) for students who ask.
Day 2 · Direct instruction: A search that stops in its loop condition
- Searching in the condition (slides 8–9; 4.14.A.1). Read the
whilecondition on slide 9 aloud: “keep going while there are elements left and this element is not the target.” The body only movesindexforward. Tracefloorswith target 12 on the board, one row per check: 3, 8, 5 keep going; 12 stops it withindexat 3, so it printsFound at 3. - Two ways the loop ends. When the loop stops, either
index < floors.length(it stopped on the target) orindex == floors.length(every element was checked). That is why theifafter the loop testsindex < floors.length. RunWhileSearch, thenWhileMissing(target 70):indexreaches 5, the length, and the program prints70 not found.
Day 2 · Direct instruction: Guard the array access
Show slide 10, with the two checks swapped and a missing target. Ask the class: “&& means both must be true, so does the order matter?” Then trace: index reaches 5, and the condition evaluates floors[5] first. The program crashes with ArrayIndexOutOfBoundsException: Index 5 out of bounds for length 5 before index < floors.length is ever checked. Connect it to short-circuit evaluation (Topic 2.5): in a && b, Java skips b when a is false, so the index check on the left protects the element check on the right. Run WhileOrderBug if the IDE is ready.
Misconception: The order of the two checks does not matter
From Topic 2.5, students know a && b and b && a give the same value, so they assume the order is a matter of style. It is not, when one side can crash: the left side runs first and decides whether the right side runs at all. The crash appears only when the target is missing, so it slips past a quick test. Worksheet question 3, snippet 2, and the Watch Out after it test this.
Day 2 pause and try: which index?
Show slide 11. Students write both answers on mini whiteboards before you reveal: target 2 prints 1 (the 2 at index 3 is never reached), and target 5 prints 5, the length of the array, meaning “not found.” Ask why rolls[5] was never read (short-circuit evaluation).
Day 2 · Direct instruction: Counting comparisons
- What to count (slides 12–13). A comparison is one check of an element against the target. Recall the counter variable from Topic 2.12. On slide 13, point to two lines:
comparisons = 0;at the start of each search, andcomparisons++;right before theif, so the comparison that finds the target is counted too. - The rule. Cover the slide’s table and have students fill it in: 40 at index 0 costs 1; 62 at index 2 costs 3; 9 at index 5 costs 6; 77, missing, costs 6. Generalize together: a target found at index
kcostsk + 1comparisons; a missing target costs one comparison per element. The output on slide 13 is3, then6. - Best and worst case. The fewest is 1 (the target is first); the most is one per element, when the target is last or missing. Run
CountGrowth: a missing target costs 10 comparisons in a 10-element array and 20 in a 20-element array, the same “single loop” growth as Topic 2.12.
Misconception: The counter goes after the if
Students put comparisons++ at the bottom of the loop body, as they did for statement counts in Topic 2.12. On the pass that finds the target, return i; leaves before the counter runs, so every successful search is one short; a failed search still counts correctly, which hides the bug. Show CounterPlacementBug (90 reports 2 instead of 3). The rule: the counter goes next to the thing counted, before anything that can end the method. Worksheet question 6, version 3, is this exact bug.
Day 2 pause and try: best case, worst case
Show slide 14. Students answer A, B, and C on mini whiteboards: (A) 1, when the target is the first element checked; (B) 38, because index 37 means indexes 0 through 37; (C) 200, when the target is the last element (index 199) or not in the array at all. Many students give 37 for B; ask them to count the indexes from 0 to 37 on a short example, such as index 2 costing 3.
Day 2 · Closure: Closure
Ask students to finish two sentences: “Found at index k costs _ comparisons” and “A missing target costs _.” (k + 1; one per element.) Homework is worksheet question 3: four snippets on the array {4, 9, 2}, one of them the swapped while condition and one calling indexOf on an array.
Day 3 · Warm-up: Check worksheet question 3
Take answers for question 3 by snippet (prints 2; crashes reading a[3]; prints 3, the length; does not compile because arrays have no indexOf). Spend the time on snippet 4: indexOf is a String method, and an array has only length. Today’s searches stay hand-written for the same reason.
Day 3 · Direct instruction: Searching an ArrayList of strings
- Two swaps (slides 15–16; 4.14.A.1). Compare slide 16’s
findwithfindIndexline by line:list.size()replacesvalues.length,list.get(i)replacesvalues[i], and.equals(t)replaces==. Everything else, including bothreturnstatements, is unchanged. - equals is exact. Cover the output and ask for
find(songs, "tides"). It is-1:equalscompares characters, andtandTare different characters. RunSearchNamesfor the same point with"maya". - Why never
==. RunEqualsBug: the roster contains"Maya", but a search fornew String("Maya")with==returns-1, because==asks whether two references point to the same object (Topic 2.6). The worksheet’s Fair Question after question 5 explains why==sometimes seems to work. - Is it there, or where is it? Show
HasName: an enhancedforloop can saytrueorfalse, but it has no index, so it cannot return a position. Use an indexed loop whenever the search must report where.
Misconception: == works for strings because it worked for ints
The int search used ==, and string searches with literals often seem to work, so students carry == over. A search that works only some of the time is the hardest kind to debug. Make .equals( part of the pattern students recite for any object search. Worksheet question 5 offers names.get(i) == target as a decoy and calls find with new String("Omar") so the decoy visibly fails.
Day 3 · Direct instruction: Start at the end
- Three changes (slide 17; 4.14.A.1, “from either end”). The loop starts at
values.length - 1, continues whilei >= 0, and counts down withi--. Theif, both returns, and the counter are unchanged. Cover the output and tracelastIndex(temps, 58): 70, then 58 at index 3, so3 after 2. ThenlastIndex(temps, 61): all five elements, ending at index 0, so0 after 5. - Which copy, and which count. A forward search for 58 returns index 1; backward returns index 3, the last copy. Counts are measured from the end where the search starts. Searching backward is how to find the most recent entry in a log: show
LatestVisit. - A missing target still costs one comparison per element in either direction (
SearchBackward, target 70).
Misconception: Start a backward search at length
The last valid index is length - 1, but length is the number students see. Starting at values.length reads one past the end on the very first pass and crashes whether or not the target is there. Show BackwardStartBug. Worksheet question 9’s third line names the crash, and question 4’s other decoy tile (i > 0) is the matching mistake at the other end: it never checks index 0.
Day 3 · Direct instruction: A 2D array, one row at a time
- Each row, then a linear search (slide 18; 4.14.A.2). A 2D array is an array of rows, and
grid[r]is one row, an ordinary 1D array (Topic 4.11). Solocateloops over the row indexes and hands each row to the samefindIndexfrom Part 1. Tracelocate(bins, 41): row 0{14, 3, 27}returns-1; row 1{8, 41, 19}returns 1, solocatereturns"row 1, col 1"and row 2 is never searched.locate(bins, 50)searches all three rows and returns"not found"after the loop. - Nested loops work too.
SeatChartwrites the same row-by-row search with nested enhancedforloops, comparing names withequals. Either way the search finishes row 0 before starting row 1, so a duplicate in an earlier row wins (row-major order, Topic 4.12). - Counting. If a counter is reset once per whole-grid search, each full row without the target adds its whole length. Run
SearchGrid: 61 in a 3-by-4 grid costs 4 + 3 = 7 comparisons; a missing target costs 3 × 4 = 12.
Misconception: Not found after the first row
This is Day 1’s else bug in two dimensions: a return "not found"; inside the outer loop ends the method after row 0. Show GridReturnBug (61 reports not found). One row without the target says nothing about the other rows; “not found” goes after the outer loop.
Day 3 pause and try: count the comparisons in a grid
Show slide 19: a 3-by-6 grid whose only target is at row 1, column 4. Students answer on mini whiteboards: all of row 0 (6) plus columns 0 through 4 of row 1 (5) is 11. Common wrong answers: 10 (forgot the comparison that matches), 5 (added the row and column numbers), and 18 (the whole grid).
Day 3 · Independent practice: Independent practice
In pairs, students work worksheet question 2 (about six minutes): six calls to locate on a 3-by-4 parking-lot grid, each with what it returns and its comparison count. Read the Think First box above it aloud first. Check locate(lot, 7): 7 appears in rows 0 and 2, and the search returns row 0, col 2 after 3 comparisons.
The rest of the worksheet is homework: questions 4, 5, 6, and 9 (code tiles for a backward search, the snippet pool for an ArrayList<String> search, the match-up on counts and direction, and the face-off between front-to-back and back-to-front).
Day 3 · Closure: Closure and exit ticket
Flash slide 20 (vocabulary) and ask for one word each: the value being sought (target), a value that can never be a real answer (sentinel value). Then slide 21’s sentence starter as a ten-second pair-share: “A search can stop as soon as an element equals the target, but it can only return -1 after every element has been checked.”
Give the exit ticket (about seven minutes). Question 1 traces a backward search with a counter, a duplicate, and a missing target (4.14.A.1, either end, results of a search); question 2 checks a row-by-row search of a 2D String array (4.14.A.2); question 3 asks students to choose a correct linear search of an ArrayList<String> (4.14.A.1). Re-teach the weakest one at the start of Topic 4.15; sorting algorithms build on the same traversal habits.