Sorting Algorithms AP CSA

Sorting Algorithms in AP CSA: Complete Guide (2025-2026)

AP CSA tests two sorting algorithms: selection sort and insertion sort. Both are O(n²) and sort in place. You need to trace them step by step, spot broken swap code, and calculate comparison counts. This is Unit 4 content (Data Collections, 30–40% of the exam).

Selection Sort

  • Outer loop: i from 0 to arr.length − 2
  • Inner loop: j from i+1 to arr.length − 1 — finds minimum index in unsorted portion
  • Swap arr[i] with arr[minIdx]
  • After pass i, arr[0..i] is in final position
  • Always makes exactly n(n−1)/2 comparisons

Insertion Sort

  • Outer loop: i from 1 to arr.length − 1
  • Save key = arr[i]; shift elements greater than key rightward
  • Place key in the gap
  • After pass i, arr[0..i] is sorted
  • Efficient on nearly-sorted data

Exam tip: trace questions ask “after k passes”—not after fully sorted. Always trace exactly k outer-loop iterations, not more.

Code Examples

Example 1: Selection Sort

After sorting {64, 25, 12, 22}, what does the output show?
public class SelectSort {
    public static void selectionSort(int[] arr) {
        for (int i = 0; i < arr.length - 1; i++) {
            int minIdx = i;
            for (int j = i + 1; j < arr.length; j++)
                if (arr[j] < arr[minIdx]) {
                    minIdx = j;
                }
            int tmp = arr[i];
            arr[i] = arr[minIdx];
            arr[minIdx] = tmp;
        }
    }
    public static void main(String[] args) {
        int[] data = {64, 25, 12, 22};
        selectionSort(data);
        for (int v : data) System.out.print(v + " ");
    }
}

Example 2: Insertion Sort

What sorted order does {5, 3, 8, 1, 4} produce?
public class InsertSort {
    public static void insertionSort(int[] arr) {
        for (int i = 1; i < arr.length; i++) {
            int key = arr[i];
            int j = i - 1;
            while (j >= 0 && arr[j] > key) {
                arr[j + 1] = arr[j];
                j--;
            }
            arr[j + 1] = key;
        }
    }
    public static void main(String[] args) {
        int[] data = {5, 3, 8, 1, 4};
        insertionSort(data);
        for (int v : data) System.out.print(v + " ");
    }
}

Example 3: Tracing Pass-by-Pass

What does {3, 1, 4, 2} look like after each selection sort pass?
public class SortTrace {
    public static void main(String[] args) {
        int[] arr = {3, 1, 4, 2};
        for (int i = 0; i < arr.length - 1; i++) {
            int minIdx = i;
            for (int j = i + 1; j < arr.length; j++)
                if (arr[j] < arr[minIdx]) {
                    minIdx = j;
                }
            int tmp = arr[i]; arr[i] = arr[minIdx]; arr[minIdx] = tmp;
            System.out.print("Pass " + (i+1) + ": ");
            for (int v : arr) System.out.print(v + " ");
            System.out.println();
        }
    }
}

Common Pitfalls

1. Broken Swap

Save the original value FIRST: tmp=arr[i]; arr[i]=arr[minIdx]; arr[minIdx]=tmp;. Skipping tmp destroys the original value.

2. Off-by-One on Outer Loop

Both sorts: outer loop ends at arr.length - 1. The last element lands in place automatically.

3. Wrong Pass Count

After k passes, the first k elements are finalized. Pass k corresponds to outer loop iteration i = k−1.

4. Assuming Selection Sort Can Exit Early

Selection sort always makes n(n−1)/2 comparisons. It does NOT detect a sorted array.

AP Exam Tip: Trace sort questions require showing exactly which elements swapped or shifted. Work it out on scratch paper before choosing an answer.
⚠ Watch Out: MCQ asks "after k passes," not "after sorting is complete." Do NOT sort the whole array in your head—trace exactly k outer-loop iterations.

Check for Understanding

Score: 0 / 0 answered (8 total)
1. After one outer-loop pass of selection sort on {{6, 2, 8, 1, 4}}, what is the array? PREDICT.
2. After one pass of insertion sort on {{5, 3, 8, 1}}, what is the array? PREDICT.
3. Spot the bug. WHICH line is wrong in this selection sort?
int minIdx = i;
for (int j = i+1; j < arr.length; j++)
    if (arr[j] < arr[minIdx]) {
        minIdx = j;
    }
int tmp = arr[i];
arr[i] = arr[minIdx];
arr[minIdx] = arr[i];   // ← line X
4. How many total comparisons does selection sort make on an array of length 5? PREDICT.
5. Three statements about selection and insertion sort. WHICH are true?

I. Selection sort always makes the same number of comparisons regardless of input order.
II. Insertion sort is more efficient on nearly-sorted arrays than selection sort.
III. Both have O(n²) worst-case runtime.
6. After 2 outer-loop passes of insertion sort on {{9, 4, 2, 7}}, what is the array? PREDICT.
7. WHICH correctly completes the three-line swap in selection sort?
int tmp = arr[i];
arr[i] = arr[minIdx];
________ = tmp;
8. A student says insertion sort exits early once the array is sorted. WHICH best describes the standard AP CSA implementation?

Frequently Asked Questions

No. Only selection sort and insertion sort are in the 2025-2026 curriculum.

Both are O(n²) worst case. Insertion sort is faster on nearly-sorted arrays because it makes fewer shifts. Selection sort always runs the same number of comparisons.

Yes: for (int j = i-1; j >= 0 && arr[j] > key; j--) arr[j+1] = arr[j]; arr[j+1] = key;. Both while and for versions are correct.

Exactly k elements are in their final sorted positions at the front of the array after k passes.

Yes. The inner loop never shifts anything, so it runs in O(n) time on a fully sorted array (the best case).

1-on-1 Expert Support

Sorting traces trip up even strong students. A targeted session with an AP CSA expert locks in the patterns before exam day.

View Tutoring Options

Related Topics

Get in Touch

Whether you're a student, parent, or teacher — I'd love to hear from you.

Just want free AP CS resources?

Enter your email below and check the subscribe box — no message needed. Students get daily practice questions and study tips. Teachers get curriculum resources and teaching strategies.

Typically responds within 24 hours

Message Sent!

Thanks for reaching out. I'll get back to you within 24 hours.

🏫 Welcome, fellow educator!

I offer curriculum resources, practice materials, and study guides designed for AP CS teachers. Let me know what you're looking for — whether it's classroom materials, a guest speaker, or Teachers Pay Teachers resources.

Email

[email protected]

📚

Courses

AP CSA, CSP, & Cybersecurity

Response Time

Within 24 hours

Prefer email? Reach me directly at [email protected]