Standard Algorithms: Searching, Sorting, Recursion
AP Computer Science A · Unit 4 — Data Collections
Searching
Sequential search checks elements one at a time from index 0. It works on any array and needs up to n comparisons.
Binary search repeatedly halves the search interval and needs only about log₂n comparisons — but it is correct only on a sorted array. On unsorted data it does not crash; it simply returns the wrong answer.
int low = 0, high = a.length - 1;
while (low <= high) {
int mid = (low + high) / 2;
if (a[mid] == key) return mid;
else if (a[mid] < key) low = mid + 1;
else high = mid - 1;
}
return -1;Sorting
Selection sort finds the smallest remaining element and swaps it into place. It always makes n(n − 1) / 2 comparisons, no matter what the data looks like.
Insertion sort takes the next element and slides it left into the already-sorted front portion. Its comparison count depends on the data: near-sorted input is fast, reverse-sorted input is worst case.
Recursion
A recursive method calls itself on a smaller input and stops at a base case. Trace one by writing the calls top-down, then combining the returned values bottom-up.
Worked example: counting the comparisons of selection sort
How many comparisons between elements does selection sort make on an array of 8 elements? Does the result depend on the initial order?
Solution
Pass 1 must examine all 8 elements to find the smallest, which is 7 comparisons. Pass 2 examines the remaining 7 elements: 6 comparisons. And so on down to the last pass with 2 elements left: 1 comparison.
Total: 7 + 6 + 5 + 4 + 3 + 2 + 1 = 28, exactly n(n − 1) / 2 with n = 8.
It does not depend on the initial order. The loop that finds the minimum always scans the entire unsorted part, even when the array is already sorted — it has no way of knowing to stop early. Only the number of swaps changes with the data.
This is what distinguishes it from insertion sort: insertion on an already sorted array costs only 7 comparisons, because each element is compared once with the element just before it and then stops immediately.
Common mistake
Trap one: running binary search on an unsorted array and then concluding “that value is not in the array”. How to prevent it — before answering any binary search question, the first thing to do is read the given array and check whether it is increasing; if not, the answer almost certainly lies in the violated premise. Trap two: mixing up the state afterk passes of the two sorting algorithms. How to prevent it — remember one sentence: selection locks the FIRST k elements into their final positions, while insertion only sorts the first k + 1 elements among themselves.Key takeaway
Binary search is faster but demands a sorted array. Selection sort costsn(n − 1) / 2 comparisons regardless of the data; insertion sort depends on the data. Recursion: trace down to the base case and then combine back up.