Skip to content

Course navigation

For teachersTopic 4.17 · Lesson kit

Recursive Searching and Sorting

  • 3 class periods
  • 45 minutes each
  • Objectives 4.17.A, 4.17.B, 4.17.C
  • 6 downloads with keys

Downloads

  • Slides

    Speaker notes on every slide

  • Lesson plan

    3 periods of 45 minutes

  • Worksheet

    Puzzles, about 30 minutes

  • Worksheet key

    Answer key

  • Exit ticket

    End of the last period

  • Exit ticket key

    Answer key

Download all AP CSA teacher filesEvery topic's slides, lesson plan, worksheet, and exit ticket, with keys (.zip)

At a glance

Pacing
3 class periods of 45 minutes
Learning objectives
4.17.A4.17.B4.17.C
Essential knowledge
4.17.A.14.17.B.14.17.B.24.17.B.34.17.C.14.17.C.2
Materials
Projector and the Split, Search, Merge slide deckWhiteboard and markersMini whiteboards or scrap paper (trace tables)IDE on every computerPrinted Split, Search, Merge puzzle worksheet (answer key for you) and exit ticket

45 minutes a day

Agenda

Day 145 minutes

  • Warm-up
  • Direct instruction
  • Guided practice
  • Independent practice
  • Closure
  1. 0:00–0:055 minWarm-upfrom a loop index to a parameter
  2. 0:05–0:1712 minDirect instructionrecursion on a String (slides 3–5)
  3. 0:17–0:2710 minDirect instructionrecursion on arrays and ArrayLists (slide 6)
  4. 0:27–0:347 minGuided practicesearching an ArrayList recursively (slide 7)
  5. 0:34–0:384 minDirect instructionpass along something smaller (slide 8)
  6. 0:38–0:435 minIndependent practiceworksheet question 1
  7. 0:43–0:452 minClosurewhat gets smaller?

Day 245 minutes

  • Warm-up
  • Direct instruction
  • Guided practice
  • Closure
  1. 0:00–0:055 minWarm-upguess my number (slide 2)
  2. 0:05–0:127 minDirect instructioncheck the middle, throw away half (slides 9–10)
  3. 0:12–0:208 minDirect instructionbinary search with a loop (slide 11)
  4. 0:20–0:288 minDirect instructionthe same search, written recursively (slide 12)
  5. 0:28–0:346 minGuided practicesearch for 8 (slide 14)
  6. 0:34–0:384 minDirect instructionunsorted data (slide 13)
  7. 0:38–0:435 minDirect instructionbinary vs. linear search (slide 15)
  8. 0:43–0:452 minClosurewhat does binary search need?

Day 345 minutes

  • Warm-up
  • Direct instruction
  • Guided practice
  • Independent practice
  • Closure
  • Exit ticket
  1. 0:00–0:055 minWarm-upgo over worksheet question 2
  2. 0:05–0:149 minDirect instructionsplit down, then merge up (slides 16–17)
  3. 0:14–0:217 minDirect instructionmerging two sorted halves (slide 18)
  4. 0:21–0:287 minGuided practicelist the merges (slide 19)
  5. 0:28–0:379 minIndependent practiceworksheet questions 4 and 5
  6. 0:37–0:403 minClosurevocabulary and how the two differ (slides 20–21)
  7. 0:40–0:455 minExit ticket

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 an ArrayList one 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.java and ExitBinarySearch.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

  1. 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.
  2. 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.
  3. Run ReverseWord.java (tac, pots). Its base case is length() <= 1, which stops one call earlier than the slide’s; ask why both work. A one-letter String is already its own reverse.
  4. Counting on the way back. Show CountLetter.java and ask for countLetter("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

  1. 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 is i == a.length: past the last element, nothing is left. Trace countEven(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.
  2. Run SumFrom.java. sumFrom(points, 0) is 20 and sumFrom(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.
  3. Work before or after the call. Show PrintBackward.java and 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.
  4. ArrayLists work the same way. FindName.java uses size() and get(index) in place of length and [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

  1. 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 a StackOverflowError. The fix is reverse(s.substring(1)).
  2. Run CountLetterNoProgress.java to show the real error. Mention that the exact message can vary between Java versions.
  3. One step too late. Show SumFromPastEnd.java, whose base case is index > nums.length, and ask what happens. At index 4, 4 > 4 is false, so the method reads nums[4] and throws an ArrayIndexOutOfBoundsException. It is the same mistake as i <= nums.length in 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

  1. Goals 2–4 (slides 3 and 9).
  2. 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 low becomes 5. The next check is index 7 (56), too big, so high becomes 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.
  3. Name the two ends. low and high mark the range still to check; mid is (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

  1. The loop version (4.17.B.3, slide 11). Read the code line by line: low starts at 0, high at nums.length - 1, and the loop runs while (low <= high). Each pass checks the middle and moves low to mid + 1 or high to mid - 1. Trace the search for 60 with the slide’s table: 16, 56, 72, and then low is 8 and high is 7, so the loop ends and the method returns -1.
  2. Ask where 60 would go. Between 56 and 72, which is exactly where low and high crossed.
  3. Run BinarySearchLoop.java, which prints low, high, and mid on every pass. Searching for 26 among nine ages takes three checks; searching for 10 ends with Index of 10: -1. Ask students to predict each line first.
  4. Why <=. Show BinarySearchLessThan.java (while (low < high)) and ask what it prints. It finds 21 but reports -1 for 26: the search narrows to low = 5 and high = 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

  1. Same steps, different shape (4.17.B.3, slide 12). In the recursive version, low and high are parameters, not local variables. The loop’s condition low <= high becomes the base case low > high, which returns -1; finding the target is the other base case. Instead of low = mid + 1 and looping again, the method calls itself with mid + 1. Go through the comparison table on the slide row by row.
  2. Run BinarySearchRecursive.java beside BinarySearchLoop.java. The first prints each call’s low and high; 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.
  3. 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

  1. 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; then low passes high and it returns -1. The 2 at index 1 was never checked.
  2. 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.

  1. 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.java to show the same numbers.
  2. Not always faster. Run SearchCompare.java on 1,000 sorted IDs. The first line is 0: 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.
  3. 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

  1. Goal 5 (slides 3 and 16).
  2. 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.
  3. Run MergeSortDemo.java, which prints every merge. Read the code with the class: the base case is nums.length > 1 (an array of 0 or 1 elements is left alone), left gets nums.length / 2 elements and right gets the rest, then mergeSort(left), mergeSort(right), and merge. Point to the order of the output: all three of the left half’s merges print before any of the right half’s, because mergeSort(left) finishes completely before mergeSort(right) starts.
  4. An odd length. Run MergeSortFive.java ({8, 3, 5, 1, 9}). left gets 5 / 2 = 2 elements and right gets 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

  1. 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 left is used up and 50 is copied as a leftover. The result is [4, 8, 15, 19, 27, 33, 41, 50].
  2. 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.
  3. 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 new int array (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.

Exit ticket

Question 1 · Multiple choice

What does this program print?

ExitStars.java
public class ExitStars
{
    public static String stars(String word)
    {
        if (word.length() == 0)
        {
            return "";
        }
        String first = word.substring(0, 1);
        if (first.equals("o"))
        {
            return "*" + stars(word.substring(1));
        }
        return first + stars(word.substring(1));
    }

    public static void main(String[] args)
    {
        System.out.println(stars("robot"));
    }
}
  1. t*b*r
  2. r*bot
  3. r*b*t
  4. rbt
Check your reasoning

C. Each call handles the first letter of its String and passes word.substring(1) to the next call, so the calls get "robot", "obot", "bot", "ot", "t", and "" (the base case, which returns ""). On the way back, each call puts its own letter, or * for an o, in front of the rest: "t", "*t", "b*t", "*b*t", "r*b*t".

A builds the answer backward; that would need stars(...) first and the letter after it, as in reverse. B stops replacing after the first o, but every call checks its own letter. D drops the o’s instead of replacing them with *.

Question 2 · Multiple choice

levels is sorted. Which statement about the two calls to search in main is correct?

ExitBinarySearch.java
public class ExitBinarySearch
{
    public static int search(int[] nums, int target, int low, int high)
    {
        if (low > high)
        {
            return -1;
        }
        int mid = (low + high) / 2;
        if (nums[mid] == target)
        {
            return mid;
        }
        else if (nums[mid] < target)
        {
            return search(nums, target, mid + 1, high);
        }
        else
        {
            return search(nums, target, low, mid - 1);
        }
    }

    public static void main(String[] args)
    {
        int[] levels = {6, 11, 15, 22, 29, 34, 40, 47};
        System.out.println(search(levels, 34, 0, 7));
        System.out.println(search(levels, 13, 0, 7));
    }
}
  1. Searching for 34 checks indexes 4, 6, and 5 and returns 5; searching for 13 returns -1; a linear search from index 0 checks 6 elements to find 34.
  2. Searching for 34 checks indexes 3 and 5 and returns 5; searching for 13 checks indexes 3, 1, and 2 and returns -1; a linear search from index 0 checks 6 elements to find 34.
  3. Searching for 34 checks indexes 3 and 5 and returns 34; searching for 13 returns -1; a linear search from index 0 checks 6 elements to find 34.
  4. Searching for 34 checks indexes 3 and 5 and returns 5; searching for 13 checks indexes 3, 1, and 2 and returns -1; a linear search from index 0 checks 5 elements to find 34.
Check your reasoning

B.

Searching for 34:

low high mid nums[mid] Next
0 7 3 22 right
4 7 5 34 found: returns 5

Searching for 13:

low high mid nums[mid] Next
0 7 3 22 left
0 2 1 11 right
2 2 2 15 left
2 1 low > high: returns -1

The program prints 5, then -1. Each check moves low to mid + 1 or high to mid - 1, because the middle was already checked. A linear search checks 6, 11, 15, 22, 29, 34: six elements, against binary search’s two.

A rounds (0 + 7) / 2 up to 4, but int division drops the remainder, so the first mid is 3. C returns the value found, but search returns mid, the index. D counts the index of 34 (5) instead of the elements checked: indexes 0 through 5 are six elements.

Question 3 · Multiple choice

Merge sort, as in class (the left part gets length / 2 elements), runs on {16, 4, 11, 7, 2}. Which list gives every merge in the order it happens?

  1. [16] + [4], then [11] + [7], then [7, 11] + [2], then [4, 16] + [2, 7, 11]
  2. [16] + [4], then [4, 16] + [11], then [7] + [2], then [4, 11, 16] + [2, 7]
  3. [16] + [4], then [11] + [7], then [4, 16] + [7, 11], then [4, 7, 11, 16] + [2]
  4. [16] + [4], then [7] + [2], then [11] + [2, 7], then [4, 16] + [2, 7, 11]
Check your reasoning

D.

  1. [16] and [4] into [4, 16]
  2. [7] and [2] into [2, 7]
  3. [11] and [2, 7] into [2, 7, 11]
  4. [4, 16] and [2, 7, 11] into [2, 4, 7, 11, 16]

The first split gives left 5 / 2 = 2 elements, [16, 4], and right the other three, [11, 7, 2], in their original order. The left half is sorted completely (merge 1) before the right half starts. The right half splits into 3 / 2 = 1 element, [11], and [7, 2], so [7, 2] must be merged (merge 2) before [11] can join it (merge 3). Merge 4 joins the two sorted halves.

A splits the right half the wrong way: its left part gets 3 / 2 = 1 element, [11], not [11, 7]. B gives the left part the larger half, 3 elements, but 5 / 2 is 2 in int division. C merges neighbors in pairs across the whole array, but merge sort finishes sorting each half before it merges the two halves.