Skip to content

Course navigation

For teachersTopic 4.15 · Lesson kit

Sorting Algorithms

  • 3 class periods
  • 45 minutes each
  • Objective 4.15.A
  • 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.15.A
Essential knowledge
4.15.A.14.15.A.24.15.A.3
Materials
Projector and the Sort It Out slide deckWhiteboard and markersFive index cards per pair, numbered 34, 19, 8, 27, and 15, for the Day 1 warm-upMini whiteboards or scrap paper for the pass-by-pass tracesIDE on every computer, or at least on the projectorPrinted Sort It Out 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-upsort five cards (slide 2)
  2. 0:05–0:138 minDirect instructionwhat sorted means, checking it in code (slides 3–5)
  3. 0:13–0:218 minDirect instructionselection sort by hand (slides 6–7)
  4. 0:21–0:3312 minDirect instructionselection sort in Java, swap versus slide (slides 8–9)
  5. 0:33–0:385 minGuided practiceyour turn, selection sort (slide 10)
  6. 0:38–0:435 minIndependent practicepuzzle worksheet question 1, selection column
  7. 0:43–0:452 minClosurewhich two positions trade?

Day 245 minutes

  • Warm-up
  • Direct instruction
  • Guided practice
  • Independent practice
  • Closure
  1. 0:00–0:055 minWarm-upone selection pass on the board
  2. 0:05–0:1510 minDirect instructioninsertion sort by hand (slides 11–12)
  3. 0:15–0:2712 minDirect instructioninsertion sort in Java (slide 13)
  4. 0:27–0:314 minDirect instructionsorted so far is not final (slide 14)
  5. 0:31–0:365 minGuided practiceyour turn, insertion sort (slide 15)
  6. 0:36–0:437 minIndependent practicepuzzle worksheet question 1, insertion column, and question 5
  7. 0:43–0:452 minClosurewhy save current?

Day 345 minutes

  • Warm-up
  • Direct instruction
  • Guided practice
  • Independent practice
  • Closure
  1. 0:00–0:055 minWarm-upsame start, one pass each
  2. 0:05–0:1510 minDirect instructionsorting an ArrayList, Strings and compareTo (slides 16–17)
  3. 0:15–0:238 minDirect instructionthe two sorts side by side, counting the work (slide 18)
  4. 0:23–0:285 minGuided practicewhich sort made this? (slide 19)
  5. 0:28–0:368 minIndependent practicepuzzle worksheet questions 3 and 9
  6. 0:36–0:459 minClosureswap or shift? (slides 20–21), then the exit ticket

Overview

Three class periods. Students learn the two iterative sorts in the CED, selection sort and insertion sort, and that both work on an array or an ArrayList (4.15.A.1). Day 1 defines sorted and teaches selection sort by hand and in Java (4.15.A.2). Day 2 teaches insertion sort the same way (4.15.A.3). Day 3 moves both sorts to an ArrayList, including String values, and teaches students to tell the two apart from an in-between state.

The learning objective is about tracing: determine the result of each step. So the core skill all three days is writing the whole array after every pass. Keep one question running through the topic: “Did two values swap, or did a block shift?” Selection sort swaps the smallest remaining value into its final spot; insertion sort shifts larger sorted values right to insert the next one, and its front is sorted but not final. The deck’s closing slide is titled “Swap or shift?” for the same reason.

Everything the sorts need was taught earlier: the three-step swap and finding a minimum (Topic 4.5), the consecutive-pairs traversal (Topic 4.5), nested loops (Topic 2.11), && short-circuiting (Topic 2.5), ArrayList get, set, and size (Topic 4.8), and compareTo (Topic 1.15). Remind students of each one as it comes up rather than reteaching it. Every sort in the lesson is ascending unless a slide says otherwise.

Teacher note

The slides are the Sort It Out deck (21 slides, with speaker notes); slide numbers below refer to it. Day 1 uses slides 1–10, Day 2 slides 11–15, and Day 3 slides 16–21. The Sort It Out puzzle worksheet has 9 questions and takes about 30 minutes. Assign it by day: the selection column of question 1 on Day 1, with questions 2, 4, and 6 as homework; the insertion column of question 1 and question 5 on Day 2, with question 7 as homework; questions 3 and 9 on Day 3, with question 8 as homework. Question 3 needs both sorts and question 9 needs ArrayList, so hold them until Day 3.

The topic’s examples/ folder has a runnable file for every demonstration named below. Before Day 1, open IsSortedCheck.snippet.java, IsSortedBounds.snippet.java, SelectionSort.java, SwapNoTemp.java, and SelectionDescending.java in the IDE; before Day 2, InsertionSort.java, InsertionShiftTrace.java, InsertionLostValue.java, and InsertionAndOrder.java; before Day 3, SortArrayList.java, StringLessThan.java, and CountWork.java.

Day 1 · Warm-up: Sort five cards

Show slide 2 and hand each pair five index cards: 34, 19, 8, 27, 15. Partners shuffle them into the slide’s order, put them in order smallest first, and then write down exactly what they did, as steps someone else could follow. Give three minutes.

Collect two descriptions. Most pairs do one of the two things the slide asks about: they look for the smallest card and move it to the front, then repeat; or they pick up one card at a time and slide it into place among the cards already in order. Write both on the board and say: “Those are the two algorithms we learn this week. The first is selection sort; the second is insertion sort.” Keep the board notes: Day 2 comes back to the second one.

Day 1 · Direct instruction: What sorted means

  1. Goals (slide 3). Goals 1–2 are today’s, goal 3 is Day 2’s, and goals 4–5 are Day 3’s.
  2. Sorted, ascending, descending (slides 4–5). A list is sorted when its elements are in order by some rule. Ascending: each element is less than or equal to the next (smallest first). Descending: largest first. Point to the two 5s on slide 5: “or equal to” means repeats are fine.
  3. Checking only neighbors. Ask: “To check that the array is sorted, do I have to compare every element with every other one?” No: if every neighboring pair is in order, the whole array is. Walk the loop on slide 5: it is the consecutive-pairs traversal from Topic 4.5. Run IsSortedCheck.snippet.java to show one true and one false.
  4. Why i < a.length - 1. Ask why the loop stops one early. Run IsSortedBounds.snippet.java, which loops to the last index: the comparison asks for scores[5] in a 5-element array and throws an ArrayIndexOutOfBoundsException. Five elements have only four neighboring pairs.

Misconception: Letting the index run to the last element

Most traversals visit every index, so students write i < arr.length out of habit. When the body also reads arr[i + 1], the last pass reads past the end. Give them the rule: if the loop body looks at the next element, stop one early.

Day 1 · Direct instruction: Selection sort by hand

  1. The steps (4.15.A.2, slides 6–7). Each pass finds the smallest value in the unsorted part and swaps it with the first unsorted element. The sorted part at the front grows by one each pass. Show slide 7 one row at a time. Before each reveal, ask: “What is the smallest value left, and which two positions trade?” Pass 1: 8 trades with 34. Pass 2: 15 trades with 19. Pass 3: 19 trades with 34. Pass 4: 27 is already in place, so it swaps with itself and nothing changes, but the pass still happens.
  2. Final position. The shaded values on slide 7 are in their final positions: each is the smallest of everything that was left, so nothing later can belong in front of it. They never move again.
  3. n − 1 passes. Ask why five elements need only four passes. After four values are placed, the one left must be the largest, so it is already in place.
  4. Smallest or largest. The CED says selection sort selects the smallest or largest element. Selecting the largest each pass and swapping it to the front sorts into descending order; the structure is the same. You will show it in Java in a moment.

Day 1 · Direct instruction: Selection sort in Java

  1. Code matched to the steps (slide 8). The outer loop’s i is the next spot to fill, from 0 while i < arr.length - 1: n − 1 passes. minIndex starts at i every pass. The inner loop scans j from i + 1 to the end and remembers the position of the smallest value seen so far: the find-the-minimum traversal from Topic 4.5. Then one three-step swap with temp. It is a nested loop (Topic 2.11) whose inner loop gets shorter each pass.
  2. Trace pass 1 on the board. For {34, 19, 8, 27, 15}, minIndex goes 0, then 1 (19), then 2 (8), and stays at 2 for 27 and 15. The swap trades arr[0] and arr[2]. Students record minIndex after each j in a small table, as in the study guide.
  3. Live demo. Run SelectionSort.java, which prints the array after each pass on the guide’s data, 29 12 45 7 18. Have students write the pass-1 and pass-3 states before you run it.
  4. Swap, not slide (slide 9). Show only the start row and ask a volunteer for the array after pass 1. Then reveal both rows: right is 8 19 34 27 15, where only positions 0 and 2 changed; wrong is 8 34 19 27 15, where 34 and 19 slid right.
  5. Why temp. Run SwapNoTemp.java, which swaps with two lines and no temp. It prints 7 7 7 7 18: the first assignment destroys a value before the second line can use it. Then run SelectionDescending.java: changing < to > (and the name to maxIndex) selects the largest each pass and sorts largest first.

Misconception: Shifting instead of swapping

“Move the smallest to the front” sounds like inserting, so students slide everything over and write 8 34 19 27 15. Selection sort trades exactly two elements; everything else stays put. Ask on every pass: “Which two positions trade?” Slide 9 and worksheet question 2’s choice B target this.

Misconception: Swapping without a temporary variable

“a gets b, b gets a” sounds like a swap, so students write two assignments. The first one overwrites a value before the second can copy it, and the array fills with copies. The SwapNoTemp.java demo shows the damage; the fix is the three-step swap from Topic 4.5.

Misconception: Setting minIndex once, outside the outer loop

Students write int minIndex = 0; or put it above the outer loop, so every pass compares against an old position. Each pass’s search must start at the first unsorted spot: minIndex = i, inside the outer loop. Slide 8’s callout says “Reset minIndex = i every pass.” Worksheet question 6 is this bug.

Day 1 · Guided practice: Your turn, selection sort

Slide 10. Students write the array after each of the first three passes of 40 25 10 35 20 on mini whiteboards, then show them on your signal. Answers: after pass 1, 10 25 40 35 20 (10 swaps with 40); after pass 2, 10 20 40 35 25 (20 swaps with 25); after pass 3, 10 20 25 35 40 (25 swaps with 40). Have students check that each pass changed exactly two positions, or none.

Day 1 · Independent practice: Independent practice

Hand out the puzzle worksheet. Students fill in the selection sort column of question 1 (pencil check, 38 14 52 9 27). Circulate and look at pass 2: 14 is already in place, so the array does not change, and students who expect every pass to change something will invent a swap.

Teacher note

Homework: questions 2 (you’re the JVM: selection sort stopped after two passes), 4 (code tiles: build one selection pass; the > tile is the decoy), and 6 (one-token fix: minIndex = 0 should be minIndex = i). The Think First box above question 6 asks whether each sort’s front part is finished; tell students to guess in the margin, since question 7 on Day 2 settles it. Students keep the worksheet for all three days.

Day 1 · Closure: Closure

Ask: “After pass 2 of selection sort on an array of 7 different numbers, what is at index 0 and index 1, and can they move again?” Students answer on scrap paper: the two smallest values in the whole array, in order, and no, they are in their final positions.

Day 2 · Warm-up: One selection pass on the board

Write 46 31 58 12 27 on the board. Students write the array after one pass of selection sort: 12 31 58 46 27 (12 and 46 trade). Then point to the board notes from Day 1: the other way to sort the cards was to take one card at a time and slide it into place. That is today’s algorithm.

Day 2 · Direct instruction: Insertion sort by hand

  1. The steps (4.15.A.3, slides 11–12). The first element alone counts as sorted. Each pass takes the next value, the first one in the unsorted part, shifts every larger sorted value one spot right, and inserts the value in the gap. Compare it to sorting a hand of playing cards.
  2. Walk slide 12 on the same start as slide 7, one row at a time, asking “which values shift?” before each reveal. Pass 1 inserts 19: 34 shifts. Pass 2 inserts 8: 34 and 19 shift, 8 goes to the front. Pass 3 inserts 27: only 34 shifts. Pass 4 inserts 15: 34, 27, and 19 shift, and 15 lands after 8. Five elements again take four passes.
  3. Shifting stops. Shifting stops at the first sorted value (moving left) that is not larger than the value being inserted, or at the front of the array.
  4. Compare with selection. Put slides 7 and 12 side by side (or the two rows of the board). Same start, same end, different middles. Selection’s front holds the smallest values of the whole list; insertion’s front holds the values that started at the front, rearranged into order.

Day 2 · Direct instruction: Insertion sort in Java

  1. Code matched to the steps (slide 13). The outer loop starts at i = 1, because the element at index 0 is already a sorted part of one. current saves arr[i]. j starts at i - 1, the last sorted element, and walks left. The while loop shifts while j >= 0 && arr[j] > current, and the value goes into arr[j + 1] when the loop stops. It is a while loop (Topic 2.7) because the number of shifts is not known in advance: 1, 2, 1, and 3 on slide 12.
  2. One shift at a time. Run InsertionShiftTrace.java, which prints the array after every single shift while inserting 7 into 12 29 45 7 18. Point out that a value appears twice in the middle steps: shifting copies, and the next step (or the insert) overwrites the old copy. The 7 is safe because it was saved in current first.
  3. Two reasons to stop. On the board, trace pass 2 of slide 13 (current is 8): 34 shifts, 19 shifts, j becomes −1, and j >= 0 stops the loop; 8 goes into arr[0]. Then pass 3 (current is 27): 34 shifts, 19 > 27 is false, and the loop stops at the first value that is not larger; 27 goes into arr[2]. Because && short-circuits (Topic 2.5), arr[-1] is never read.
  4. Why current. Run InsertionLostValue.java, which uses arr[i] instead of a saved copy. It prints 29 29 45 45 45: the first shift writes over arr[i], and the value to insert is gone.
  5. Why that order. Run InsertionAndOrder.java, which writes the condition as scores[j] > current && j >= 0. It throws an ArrayIndexOutOfBoundsException for index −1 as soon as a value must reach the front.

Misconception: Not saving the value before shifting

Students read arr[i] in the condition and the insert, because “the current element is at index i.” The first shift copies a larger value into arr[i], so the value being inserted is lost and the program prints copies. The InsertionLostValue.java demo shows it; the worksheet’s Watch Out box after question 5 says the same thing.

Misconception: Writing the two conditions in the wrong order

In everyday logic “A and B” is the same as “B and A,” so students put arr[j] > current first. Java checks the left side first, so when j is −1 it reads arr[-1] and crashes. The bounds check must come first: j >= 0 && arr[j] > current. Worksheet question 5’s pool includes the reversed condition and j > 0 as traps.

Day 2 · Direct instruction: Sorted so far is not final

Slide 14. Show the two arrays and ask: “In which one are the front values done?” Selection after 2 passes, 8 15 34 27 19: 8 and 15 are the two smallest of all, so they are final. Insertion after 1 pass, 19 34 8 27 15: 19 and 34 are in order, but 8 has not been looked at yet and will push in front of both on the next pass. The CED wording is exact: insertion sort puts an element into its correct (but not necessarily final) position in the sorted portion.

Misconception: Thinking each inserted element is in its final position

Both sorts build a sorted part at the front, and selection sort’s really is final, so students assume insertion sort’s is too. Ask: “Has the sort looked at every value yet?” Insertion sort’s sorted part holds only the values it has reached. Worksheet question 7 (two truths and a lie) asks exactly this.

Day 2 · Guided practice: Your turn, insertion sort

Slide 15. Students write the array after passes 1, 2, and 3 of 35 15 25 5 45 and count the shifts. Answers: pass 1 inserts 15 (35 shifts), 15 35 25 5 45; pass 2 inserts 25 (35 shifts), 15 25 35 5 45; pass 3 inserts 5 (35, 25, and 15 shift), 5 15 25 35 45. The shifts are 1, 1, and 3. Ask how many shifts pass 4 needs (none: 45 is larger than everything in front of it).

Day 2 · Independent practice: Independent practice

Students fill in the insertion sort column of question 1, then work question 5 (snippet pool: complete the insertion sort). In question 1, watch pass 2 (52 does not shift anything) and pass 3 (9 slides to the front past three values). In question 5, ask students who pick arr[j] > current && j >= 0 what happens when 1 reaches the front.

Teacher note

Homework: question 7 (two truths and a lie). It settles the Think First guess from Day 1: claim 2, “4 is in its final position,” is the lie.

Day 2 · Closure: Closure

Ask: “Why does insertion sort save arr[i] in current before the while loop?” Students answer on scrap paper: the first shift copies a larger value into arr[i], so without the saved copy the value to insert would be gone.

Day 3 · Warm-up: Same start, one pass each

Write 50 20 40 10 30 on the board. Half the class writes the array after one pass of selection sort, the other half after one pass of insertion sort. Answers: selection, 10 20 40 50 30 (10 and 50 trade); insertion, 20 50 40 10 30 (50 shifts, 20 inserted). Ask: “If I showed you only the result, how could you tell which sort made it?” Leave the question open; slide 18 answers it.

Day 3 · Direct instruction: Sorting an ArrayList

  1. Same steps, new syntax (4.15.A.1, slides 16–17). Both sorts work on an ArrayList. Write the translation on the board, as in Topic 4.10: arr.length becomes list.size(), arr[j] becomes list.get(j), and arr[j] = x; becomes list.set(j, x);. Sorting uses set, never add or remove: the list never changes size, values only trade or shift places.
  2. Strings need compareTo (slide 17). Point to the while condition: list.get(j).compareTo(current) > 0 means “list.get(j) comes after current” (Topic 1.15). Trace the names: insert Ben (Pia shifts), insert Zara (nothing shifts), insert Cal (Zara and Pia shift; Ben comes before Cal, so shifting stops). Output: [Ben, Cal, Pia, Zara].
  3. Live demo. Run SortArrayList.java: selection sort on an ArrayList<Integer> of lap times (the < still works because each Integer unboxes, Topic 4.7), then insertion sort on names, printing every pass. Then run StringLessThan.java, which compares two String values with >: it does not compile (bad operand types for binary operator '>').

Misconception: Comparing String values with > or <

“Comes later alphabetically” feels like “greater than,” so students copy the array version onto an ArrayList<String> unchanged. The relational operators work only on numbers (and Integer values, by unboxing). Strings need compareTo. Worksheet question 9, snippets 2 and 4, contrasts the two.

Misconception: Using square brackets on an ArrayList

Students translating array code leave list[j] behind. An ArrayList has no [ ]; reading is get and writing is set. Worksheet question 9, snippet 3, is this error.

Day 3 · Direct instruction: The two sorts side by side

  1. The comparison table (slide 18). Reveal one row at a time and ask students to fill in each cell before you show it. The two rows that identify a sort: what moves (exactly two values trade, or a block slides right one spot) and the front part (the smallest of the whole list and final, or the original front values in order and not final). The back part row adds a check: insertion sort has not touched anything it has not reached.
  2. Answer the warm-up. 10 20 40 50 30 has the smallest value of the whole list at the front, and 50 jumped from index 0 to index 3: selection. 20 50 40 10 30 has only the first two original values rearranged, and indices 2–4 untouched: insertion.
  3. Counting the work (last row of slide 18). On 8 values already sorted, selection sort makes 7 + 6 + … + 1 = 28 comparisons, and insertion sort makes 0 shifts. Ask why selection cannot stop early: it cannot know a value is the smallest without comparing it to everything left. Run CountWork.java: selection makes 10 comparisons on every 5-element array; insertion makes 6 shifts on a mixed array, 0 on a sorted one, and 10 on a reversed one. This is the statement-counting from Topic 2.12.

Misconception: Judging the algorithm by how sorted the list looks

Students guess “selection” for whichever state looks more sorted. That is not reliable. Teach them to look for evidence: are the front values the smallest in the whole list, and did exactly two values trade (selection)? Or are they the original front values, with the back untouched (insertion)? Worksheet question 3 includes a state that looks sorted at the front but was made by sliding, which neither sort does.

Day 3 · Guided practice: Which sort made this?

Slide 19. Both states started as 9 3 7 1 8 and ran 2 passes. Partners decide which sort made each and write one piece of evidence. Answers: A (1 3 7 9 8) is selection: 1, the smallest of all, swapped to the front, and 3 was already second. B (3 7 9 1 8) is insertion: the original first three, 9, 3, and 7, are in order, and 1 and 8 have not moved. Ask: “Could insertion sort have put 1 at the front after 2 passes?” No: it does not reach index 3 until pass 3.

Day 3 · Independent practice: Independent practice

Students work question 3 (match-up: five states of 8 5 6 1 4, matched to selection or insertion after 1 or 2 passes, or a sliding mistake) and question 9 (you’re the compiler: get, set, <, and compareTo on an ArrayList<Integer> and an ArrayList<String>). In question 3, steer students who get stuck on state 3 (1 8 5 6 4) to ask “which two positions trade?”: 8, 5, and 6 all slid, so it is choice T.

Teacher note

Homework: question 8 (face-off), any of question 9 not finished, and any earlier questions still open. Question 8’s last line uses six sorted values (15 comparisons, 0 shifts); it is a good check that students can redo slide 18’s count for a different size.

Day 3 · Closure: Closure and exit ticket

Spend one minute on slide 20 (vocabulary): have students say the difference between swap and shift aloud. Then slide 21: partners explain how one pass of selection sort differs from one pass of insertion sort, using the sentence starter. Listen for: selection sort swaps the smallest value into a final spot, but insertion sort shifts values right to make room, and its front is not final until the end. Cold-call two pairs.

Then give the exit ticket (about five minutes). Question 1 checks selection sort’s passes (4.15.A.2), question 2 checks insertion sort’s shifts and that its placements are not final (4.15.A.3), and question 3 checks insertion sort on an ArrayList<String> (4.15.A.1). Re-teach the weakest one before the unit review; the swap-or-shift contrast is the one AP questions test most often.

Exit ticket

Question 1 · Multiple choice

Selection sort (smallest first) is applied to 7 4 9 2 6. What does the array look like after two passes?

  1. 4 7 9 2 6
  2. 2 7 4 9 6
  3. 2 4 9 7 6
  4. 2 4 6 7 9
Check your reasoning

C. Pass 1: the smallest value is 2 at index 3; it swaps with 7 at index 0, giving 2 4 9 7 6. Pass 2: the unsorted part is 4, 9, 7, 6; the smallest is 4, already first, so it swaps with itself and nothing changes.

A is insertion sort after two passes: only the first three original values, 7, 4, and 9, are put in order. B slides 7, 4, and 9 right to make room for 2; selection sort swaps exactly two values. D is the fully sorted array, which takes four passes.

Question 2 · Multiple choice

Insertion sort is applied to 30 10 40 20 50. After pass 2 the array is 10 30 40 20 50, with 30 at index 1. Which statement about pass 3 is correct?

  1. 20 swaps with 40, giving 10 30 20 40 50, and the pass ends; 30 stays at index 1, its final position.
  2. 40 and 30 each shift one place right, and 20 goes in at index 1, giving 10 20 30 40 50; 30’s place after pass 2 was not final.
  3. 20 swaps with 30, giving 10 20 40 30 50.
  4. Nothing moves, because each earlier pass already put its value in its final position.
Check your reasoning

B.

Pass Inserted Shifted Array after the pass
1 10 30 (1) 10 30 40 20 50
2 40 none (0) 10 30 40 20 50
3 20 40, 30 (2) 10 20 30 40 50

After pass 2, 30 is in its correct position among the values insertion sort has reached (10, 30, 40), but 20 has not been reached yet. In pass 3, 20 is smaller than 40 and 30, so both shift right, and 30 moves to index 2. Insertion sort places each value in its correct, but not necessarily final, position in the sorted part.

A stops after one step, but insertion sort keeps shifting until it finds a value that is not greater than 20 (here 10). C swaps 20 with the first larger value, the way selection sort swaps a minimum into place; insertion sort shifts, and here 40 must move too. D treats insertion sort’s placements as final; that is true of selection sort, not insertion sort.

Question 3 · Multiple choice

ExitSortNames.java
import java.util.ArrayList;

public class ExitSortNames
{
    public static void sort(ArrayList<String> list)
    {
        for (int i = 1; i < list.size(); i++)
        {
            String current = list.get(i);
            int j = i - 1;
            while (j >= 0 && list.get(j).compareTo(current) > 0)
            {
                list.set(j + 1, list.get(j));
                j--;
            }
            list.set(j + 1, current);
            System.out.println(list);
        }
    }

    public static void main(String[] args)
    {
        ArrayList<String> crew = new ArrayList<String>();
        crew.add("Kai");
        crew.add("Ada");
        crew.add("Max");
        crew.add("Bea");
        sort(crew);
    }
}

Which statement is correct?

  1. It prints only two lines, [Ada, Kai, Max, Bea] and [Ada, Bea, Kai, Max]; line 11 uses compareTo because > does not compile on String objects.
  2. It prints [Ada, Kai, Max, Bea], [Ada, Kai, Max, Bea], and [Ada, Bea, Kai, Max]; list.get(j) > current would work just as well, comparing the names alphabetically.
  3. It prints [Ada, Kai, Max, Bea], [Ada, Kai, Max, Bea], and [Ada, Kai, Bea, Max]; line 11 uses compareTo because > does not compile on String objects.
  4. It prints [Ada, Kai, Max, Bea], [Ada, Kai, Max, Bea], and [Ada, Bea, Kai, Max]; line 11 uses compareTo because > does not compile on String objects.
Check your reasoning

D.

[Ada, Kai, Max, Bea]
[Ada, Kai, Max, Bea]
[Ada, Bea, Kai, Max]

Pass 1 inserts Ada: Kai comes after Ada, so Kai shifts right. Pass 2 inserts Max: Kai comes before Max, so nothing shifts and the list prints unchanged. Pass 3 inserts Bea: Max and Kai shift right; Ada comes before Bea, so shifting stops and Bea goes to index 1. The relational operators > and < work only on numbers; list.get(j).compareTo(current) > 0 is true exactly when list.get(j) comes after current in dictionary order, which is when it must shift right.

A skips the pass where nothing shifts, but line 17 prints after every pass. B has the right output but thinks > compares strings; a String is an object, so list.get(j) > current does not compile. C stops pass 3 after one shift, but Kai also comes after Bea and must shift right too.