Overview
This is the last topic of Unit 4. It has three learning objectives, and the day split follows the deck’s three parts:
- Day 1 (4.17.A): recursion that traverses a
String, an array, or anArrayListone position at a time (4.17.A.1). - Day 2 (4.17.B): binary search. It needs sorted data and eliminates half of what is left with each check (4.17.B.1); it is typically more efficient than linear search (4.17.B.2); and it can be written with a loop or with recursion (4.17.B.3).
- Day 3 (4.17.C): merge sort, which splits an array until every piece has one element and then merges sorted pieces back together in order (4.17.C.1, 4.17.C.2). Exit ticket at the end.
Students already know recursion, base cases, and the call stack (Topic 4.16), linear search (Topic 4.14), selection and insertion sort (Topic 4.15), substring (Topic 1.15), arrays (Topics 4.3–4.5), and ArrayList methods (Topic 4.8). Every construct in the topic is now available, so there is no boundary to stay under except the CED’s exclusions: no search algorithms other than linear and binary, and no sorting algorithms other than selection, insertion, and merge sort. If a student asks about another one, say it is outside the course.
One idea runs through all three days: every recursive call works on something smaller. On Day 1 it is a shorter String or the next index; on Day 2 it is half of the range from low to high; on Day 3 it is half of the array. When the call does not get smaller, the program crashes with a StackOverflowError, and three of this topic’s misconceptions are that crash in different clothes.
Teacher note
The slides are the Split, Search, Merge deck (21 slides); slide numbers below refer to it. Day 1 uses slides 3–8, Day 2 uses slides 2 and 9–15 (slide 2’s warm-up is about binary search, so it waits for Day 2), and Day 3 uses slides 16–21. The Split, Search, Merge puzzle worksheet (9 questions, about 30 minutes) follows the same split: questions 1, 3, and 7 need only Day 1; questions 2, 6, and 8 need Day 2; questions 4, 5, and 9 need Day 3. Question 9 also reviews selection and insertion sort from Topic 4.15.
Every demonstration file is a full program in the topic’s examples/ folder. Open the day’s files in the IDE before class so each demo is one click.
- Day 1:
SumFrom.java,ReverseWord.java,CountLetter.java,PrintBackward.java,FindName.java,CountLetterNoProgress.java(run-time error),SumFromPastEnd.java(run-time error). - Day 2:
BinarySearchLoop.java,BinarySearchRecursive.java,BinarySearchLessThan.java,RecursiveNoProgress.java(run-time error),UnsortedSearch.java,SearchCompare.java,WorstCaseChecks.java. - Day 3:
MergeSortDemo.java,MergeSortFive.java,MergeHalves.java,MergeNoLeftovers.java,MergeSortZeroBase.java(run-time error),LockerFinder.java(extension). - Printed only (exit ticket):
ExitStars.javaandExitBinarySearch.java.
Day 1 · Warm-up: From a loop index to a parameter
Write a Topic 4.4 loop on the board that sums an int[] named points (4, 7, 1, 8). Ask two questions: “What does i do on each pass?” (it moves to the next element) and “When does the loop stop?” (when i reaches points.length). Then ask the Topic 4.16 question: “What two things does every recursive method need?” A base case, and a recursive call that moves toward it.
Tell students that today the loop variable becomes a parameter: each call handles one position and passes the next position to the next call. Leave both answers on the board; the closure comes back to them.
Day 1 · Direct instruction: Recursion on a String
- Goals (slide 3). Read the five goals; goal 1 is today, goals 2–4 are Day 2, and goal 5 is Day 3. Slide 4 opens Part 1.
- One letter shorter each call (4.17.A.1, slide 5). Walk through
reverse("frog")with the call table. Point to the two things that make it recursion on a String:s.substring(1)is every letter except the first (Topic 1.15), so each call gets a String one letter shorter, and the base case is the empty String, when nothing is left. Then read the Returns row from right to left:"","g","go","gor","gorf". Ask: “Which call finishes first?” The last one made,reverse(""), as in Topic 4.16’s call stack. - Run
ReverseWord.java(tac,pots). Its base case islength() <= 1, which stops one call earlier than the slide’s; ask why both work. A one-letter String is already its own reverse. - Counting on the way back. Show
CountLetter.javaand ask forcountLetter("moon", "o")before running it. Each call looks at its first letter, asks the recursive call to count the rest, and adds 1 if its own letter matches. It prints 3 for"banana"and 2 for"moon".
Day 1 · Direct instruction: Recursion on arrays and ArrayLists
- One index further each call (4.17.A.1, slide 6). An array cannot get shorter the way a String can, so the method takes an index parameter and passes
i + 1. The base case isi == a.length: past the last element, nothing is left. TracecountEven(a, 0)for{6, 3, 8, 5}and fill the Returns column from the bottom up, as the slide says: 0, 0, 1, 1, 2. - Run
SumFrom.java.sumFrom(points, 0)is 20 andsumFrom(points, 2)is 9: the index says where to start, so the second call adds only 1 and 8. Point back to the warm-up loop: same work, the index is now a parameter. - Work before or after the call. Show
PrintBackward.javaand ask for the output. It prints 5, 30, 12: each call makes the recursive call first and prints its own element afterward, so the last element prints first. Moving the print above the call would print in order. ArrayLists work the same way.FindName.javausessize()andget(index)in place oflengthand[index], and has two base cases: past the end (return -1) and found (return the index). It prints 2 and -1.
Misconception: Reading the answer in the order the calls were made
Students read a recursion trace top to bottom and build the answer from the first call, so reverse("frog") comes out "frog" or PrintBackward.java prints 12, 30, 5. The work after a recursive call happens on the way back, starting with the last call. Have students fill a Returns column from the bottom up every time, as on slides 5 and 6.
Day 1 · Guided practice: Searching an ArrayList recursively
Show slide 7. Pairs fill in the Returns and Calls columns on mini whiteboards for find(names, target, 0) with names holding "Ana", "Bo", "Lu", "Mia":
| target | Returns | Calls |
|---|---|---|
"Lu" |
2 | 3 (i = 0, 1, 2) |
"Zed" |
-1 | 5 (i = 0, 1, 2, 3, then 4, the base case) |
Most pairs get 4 calls for "Zed". Ask them to count again with i == names.size(): the call with i = 4 is a real call, and it is the one that returns -1. Then ask: “What search from Topic 4.14 is this?” A linear search, written recursively.
Day 1 · Direct instruction: Pass along something smaller
- No progress (slide 8).
reverse(s)passes the same String again, so the base case is never reached and the calls pile up until the program crashes with aStackOverflowError. The fix isreverse(s.substring(1)). - Run
CountLetterNoProgress.javato show the real error. Mention that the exact message can vary between Java versions. - One step too late. Show
SumFromPastEnd.java, whose base case isindex > nums.length, and ask what happens. Atindex4,4 > 4is false, so the method readsnums[4]and throws anArrayIndexOutOfBoundsException. It is the same mistake asi <= nums.lengthin a loop.
Misconception: A recursive call that passes the same value
Students write countLetter(word, letter) or reverse(s) because the call “should handle the rest,” without making the rest smaller. Every call is then identical, and the program ends in a StackOverflowError. Teach the check from slide 8: point at each recursive call and say what got smaller (a shorter String, the next index). A StackOverflowError almost always means a call that does not move toward the base case.
Misconception: Stopping one index too late
Students write index > nums.length because “past the end” sounds like “greater than.” But nums.length is already past the last index, so the base case must stop there: index == nums.length (or >=). Ask: “What is the last valid index, and what should happen at the one after it?”
Day 1 · Independent practice: Independent practice
Hand out the puzzle worksheet. Students do question 1 (you’re the JVM) alone: countE("geese") returns 3 after 6 calls, choice A. Circulate and look for B (5 calls): those students did not count the base-case call on "", the same slip as slide 7’s "Zed".
Teacher note
Homework: questions 3 (code tiles: a recursive ArrayList sum) and 7 (one-token fix: maxFrom with < instead of >). Both need only Day 1. Tell students to read the key words in question 3’s decoys: one stops one element early, and one never moves i. The rest of the worksheet waits for Days 2 and 3.
Day 1 · Closure: Closure
Point back at the warm-up board. Ask: “In a recursive method on a String, what gets smaller? On an array or ArrayList?” Students answer on scrap paper: the String, through substring(1); the part left to visit, by passing index + 1. Then: “What happens if nothing gets smaller?” A StackOverflowError.
Day 2 · Warm-up: Guess my number
Show slide 2. Play one round with the class: you pick a number from 1 to 100 and answer only “higher” or “lower.” Then pairs answer the slide’s question: at most how many guesses does each strategy need? Strategy A (1, 2, 3, …) can need 100. Strategy B (the middle of what is left) needs at most 7, because each guess cuts the possibilities in half: 100, 50, 25, 13, 7, 4, 2, 1.
Ask one more: “Strategy B only works because I say higher or lower. What would happen if the numbers were not in order?” Keep the answer for slide 13.
Day 2 · Direct instruction: Check the middle, throw away half
- Goals 2–4 (slides 3 and 9).
- The idea (4.17.B.1, slide 10). Walk through the search for 23 in the sorted array of ten values. The first check is index 4 (16), too small, so everything from index 0 to 4 is thrown away and
lowbecomes 5. The next check is index 7 (56), too big, sohighbecomes 6. The third check finds 23 at index 5. Ask: “Why can we throw away index 0 to 4 after seeing 16?” Because the data is sorted, everything to the left of 16 is smaller than 16, so it is smaller than 23 too. - Name the two ends.
lowandhighmark the range still to check;midis(low + high) / 2, with integer division. Students saw the same idea as “the middle” in the warm-up.
Day 2 · Direct instruction: Binary search with a loop
- The loop version (4.17.B.3, slide 11). Read the code line by line:
lowstarts at 0,highatnums.length - 1, and the loop runswhile (low <= high). Each pass checks the middle and moveslowtomid + 1orhightomid - 1. Trace the search for 60 with the slide’s table: 16, 56, 72, and thenlowis 8 andhighis 7, so the loop ends and the method returns -1. - Ask where 60 would go. Between 56 and 72, which is exactly where
lowandhighcrossed. - Run
BinarySearchLoop.java, which printslow,high, andmidon every pass. Searching for 26 among nine ages takes three checks; searching for 10 ends withIndex of 10: -1. Ask students to predict each line first. - Why
<=. ShowBinarySearchLessThan.java(while (low < high)) and ask what it prints. It finds 21 but reports -1 for 26: the search narrows tolow= 5 andhigh= 5, one element, the 26, and the loop ends without checking it.
Misconception: Stopping the loop when low equals high
Students write low < high because it looks like the usual loop test. A range where low equals high still holds one element, so low < high skips the last check (BinarySearchLessThan.java). The condition is low <= high; the search is over only when low has passed high.
Day 2 · Direct instruction: The same search, written recursively
- Same steps, different shape (4.17.B.3, slide 12). In the recursive version,
lowandhighare parameters, not local variables. The loop’s conditionlow <= highbecomes the base caselow > high, which returns -1; finding the target is the other base case. Instead oflow = mid + 1and looping again, the method calls itself withmid + 1. Go through the comparison table on the slide row by row. - Run
BinarySearchRecursive.javabesideBinarySearchLoop.java. The first prints each call’slowandhigh; the ranges match the loop version’s, pass for pass. The only extra line is the last call for 10,low 2, high 1, which is the base case. Both versions check the same elements in the same order. - Ask: “Each call makes how many recursive calls?” One. And it returns that call’s answer straight back, so every waiting call passes the same index (or -1) along.
Misconception: Calling with mid instead of mid + 1
Students write search(nums, target, mid, high) because “the right half starts at the middle.” The middle was already checked, and when low and high are next to each other, mid equals low, so the call gets exactly the same range forever. Run RecursiveNoProgress.java: the search for 30 works by luck, and the search for 41 ends in a StackOverflowError. This is Day 1’s rule again: every call must pass something smaller.
Day 2 · Guided practice: Search for 8
Show slide 14. Students fill in the table on mini whiteboards, then compare with a partner:
low |
high |
mid |
nums[mid] |
Next |
|---|---|---|---|---|
| 0 | 9 | 4 | 16 | go left |
| 0 | 3 | 1 | 5 | go right |
| 2 | 3 | 2 | 8 | found |
It returns 2 after three checks. Watch for students who write high = 4 in the second row: the middle was already checked, so the new high is mid - 1, which is 3.
Day 2 · Direct instruction: Unsorted data
- No crash, just a wrong answer (4.17.B.1, slide 13). Ask the warm-up question again, then show the slide. Searching
{9, 2, 14, 6, 11}for 2: the middle is 14, which is more than 2, so the search goes left; it checks 9 and goes left again; thenlowpasseshighand it returns -1. The 2 at index 1 was never checked. - Run
UnsortedSearch.java(checks 7, 18, 25, then prints -1 for a 12 that is at index 1). Binary search does not check whether the data is sorted; it trusts it. Sorted data is a precondition (skill 4.B).
Misconception: Binary search on unsorted data throws an exception
Students expect Java to complain. It cannot: every index the search uses is valid, so it runs normally and gives a wrong answer. The fix is to sort first (merge sort, tomorrow, is one way) or to use linear search, which works on any order. Worksheet question 8’s lie is this exact claim.
Day 2 · Direct instruction: Binary vs. linear search
- Worst cases (4.17.B.2, slide 15). Read the table: 10 elements need at most 4 binary checks, 1,000 need 10, and 1,000,000 need only 20. Ask: “What happens to binary search’s worst case when the data doubles?” It goes up by one check. Run
WorstCaseChecks.javato show the same numbers. - Not always faster. Run
SearchCompare.javaon 1,000 sorted IDs. The first line is0: linear 1, binary 9: when the target is the first element, linear search wins. That is why the CED says binary search is typically more efficient. - When to use which. Binary search needs sorted data and wins on big data; linear search works on any order and wins when the target is near the front.
Misconception: Binary search is always faster
Students turn “usually” into “always.” Show the first line of SearchCompare.java (1 check against 9) and ask why. Binary search always starts in the middle. Ask them to finish: “Binary search is typically faster, but linear search wins when …” (the target is near the front, or the data is not sorted).
Day 2 · Closure: Closure
Ask: “What does binary search need from the data, and what does it throw away with each check?” Students answer on scrap paper: the data must be sorted; it throws away the half that cannot hold the target.
Teacher note
Homework: worksheet questions 2 (trace the recursive search for 15: four calls, returns -1), 6 (the face-off), and 8 (two truths and a lie). Question 2 is tomorrow’s warm-up.
Day 3 · Warm-up: Go over question 2
Draw question 2’s table on the board and have students call out each row: 27 (left), 13 (right), 18 (left), then low 3 and high 2, return -1. Ask: “How many of the 11 elements were checked?” Three. Then ask one student to read the face-off’s last line from question 6: binary search is typically faster, not always.
Day 3 · Direct instruction: Split down, then merge up
- Goal 5 (slides 3 and 16).
- The whole picture (4.17.C.1, 4.17.C.2, slide 17). Read the diagram top to bottom. The split rows cut the array in half again and again, keeping the original order, until every piece has one element. A one-element piece is already sorted. Then the merge rows join sorted pieces in pairs until the whole array is sorted. Ask: “In the split rows, did any values change order?” No. Only merging compares values.
- Run
MergeSortDemo.java, which prints every merge. Read the code with the class: the base case isnums.length > 1(an array of 0 or 1 elements is left alone),leftgetsnums.length / 2elements andrightgets the rest, thenmergeSort(left),mergeSort(right), andmerge. Point to the order of the output: all three of the left half’s merges print before any of the right half’s, becausemergeSort(left)finishes completely beforemergeSort(right)starts. - An odd length. Run
MergeSortFive.java({8, 3, 5, 1, 9}).leftgets 5 / 2 = 2 elements andrightgets 3, so the right half needs one more split.
Misconception: Splitting puts the small values on the left
Students picture the split as a sorting step. It is not: it cuts at a position, so {7, 3, 5, 1} splits into [7, 3] and [5, 1] exactly as they were. The worksheet’s Watch out box after question 5 says the same. When students write a piece right after a split, ask them to copy the elements in their original order.
Misconception: A base case that lets one-element arrays through
Students write nums.length > 0, reasoning that any non-empty array needs sorting. A one-element array then splits into 0 and 1 elements, and the 1-element half does the same forever: MergeSortZeroBase.java ends in a StackOverflowError. The split never makes a one-element array smaller, so it must be the base case: nums.length > 1.
Day 3 · Direct instruction: Merging two sorted halves
- Always take the smaller front value (4.17.C.2, slide 18). Work through the Compare and Copy columns with the class: 8 vs 4 copies 4, 8 vs 19 copies 8, and so on, until
leftis used up and 50 is copied as a leftover. The result is[4, 8, 15, 19, 27, 33, 41, 50]. - Run
MergeHalves.java. Read the three loops: the first compares while both arrays have values left; the other two copy the leftovers of whichever array still has some. Its second merge ({5, 12}with{3, 8, 20, 25}) leaves two leftovers in the right array. - Why the leftover loops matter. Run
MergeNoLeftovers.java, which has only the first loop. The results end in zeros:[9, 17, 24, 30, 38, 45, 52, 0]. Those spots kept the default value 0 of a newintarray (Topic 4.3).
Misconception: The first loop handles everything
Students think the compare loop copies every value. It stops as soon as either array runs out, so the other array’s remaining values are never copied, and their spots keep the default 0. At least one leftover loop has work to do in almost every merge. Worksheet question 4’s holes 2 and 3 are these two loops.
Day 3 · Guided practice: List the merges
Show slide 19. Pairs list the merges for {12, 7, 3, 10, 5} in order. Remind them: left gets 5 / 2 = 2 elements, and the left half finishes before the right half starts.
| Merge | left | right | Result |
|---|---|---|---|
| 1 | [12] |
[7] |
[7, 12] |
| 2 | [10] |
[5] |
[5, 10] |
| 3 | [3] |
[5, 10] |
[3, 5, 10] |
| 4 | [7, 12] |
[3, 5, 10] |
[3, 5, 7, 10, 12] |
The right half [3, 10, 5] splits into [3] and [10, 5], so [10, 5] has to be merged (merge 2) before [3] can join it (merge 3). Pairs who list [3] and [10] together first have split the right half the wrong way: its left part gets 3 / 2 = 1 element.
Day 3 · Independent practice: Independent practice
Students do worksheet questions 4 and 5 alone:
- Question 4 (snippet pool):
<=,i < left.length,j < right.length. Ask early finishers why>=would be wrong: it takes the larger value first. - Question 5 (pencil check): five merges for
{29, 14, 37, 8, 21, 5}, the first given. The left half[29, 14, 37]needs merges 1 and 2 before the right half starts.
Teacher note
Homework: whatever is left of question 5, and question 9 (who am I?), which reviews selection and insertion sort from Topic 4.15 beside the three algorithms from this topic.
Day 3 · Closure: Closure
Slide 20: review the vocabulary together; ask a student to explain “worst case” with a number from yesterday’s slide 15. Then slide 21: partners finish the sentence starter. A complete answer: “Binary search calls itself on half of the data, but merge sort calls itself on both halves and then merges them.” Take two pairs’ answers aloud. If time allows, mention the guide’s LockerFinder.java, which sorts with merge sort and then searches with binary search: the sort is what makes the search valid.
Day 3 · Exit ticket: Exit ticket
Give the exit ticket for the last 5 minutes. Question 1 checks recursion on a String (4.17.A), question 2 tracing binary search and comparing it with linear search (4.17.B), and question 3 the order of merges in merge sort (4.17.C). Re-teach the weakest one with the matching slide (5, 14, or 19) before the Unit 4 review.