AP Computer Science A · Data collections
Searching and sorting
1Linear search
Linear (sequential) search checks elements one at a time until the target is found:
public static int linearSearch(int[] arr, int target) {
for (int i = 0; i < arr.length; i++) {
if (arr[i] == target) return i;
}
return -1;
}
- Works on unsorted data.
- Worst case: checks all $n$ elements (target last or absent).
- Return −1 after the loop to signal "not found".
Check yourself
In the worst case, linear search on 1,000 elements makes how many comparisons?
Show the answer
1,000
Every element.
2Binary search
Binary search works only on sorted data. It compares the target with the middle element and discards half of the remaining range each time:
int low = 0, high = arr.length - 1;
while (low <= high) {
int mid = (low + high) / 2;
if (arr[mid] == target) return mid;
else if (arr[mid] < target) low = mid + 1;
else high = mid - 1;
}
return -1;
Worst case about $\log_2 n$ comparisons: about 10 for 1,000 elements, 20 for 1,000,000.
find 23 in [3, 8, 12, 17, 23, 31, 40].
- low 0, high 6, mid 3: 17 < 23 → low = 4.
- low 4, high 6, mid 5: 31 > 23 → high = 4.
- low 4, high 4, mid 4: found at index 4.
Binary search halves the range each step: grey values have been ruled out
Check yourself
Binary search requires that the data is:
Show the answer
Sorted
Halving relies on order.
3Selection sort
Selection sort: for each position i, find the smallest element in the unsorted part (from i to the end) and swap it into position i.
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 temp = arr[i];
arr[i] = arr[minIdx];
arr[minIdx] = temp;
}
[5, 2, 9, 1].
- Pass 1: min is 1 → swap with 5 → [1, 2, 9, 5].
- Pass 2: min of [2, 9, 5] is 2 → stays → [1, 2, 9, 5].
- Pass 3: min of [9, 5] is 5 → swap → [1, 2, 5, 9].
Always makes about $\frac{n^2}{2}$ comparisons, whatever the initial order.
Check yourself
After the first pass of selection sort on [7, 3, 9, 2], the array is:
Show the answer
[2, 3, 9, 7]
Smallest swapped to the front.
4Insertion sort
Insertion sort: build a sorted section at the front. Take each next element and shift larger sorted elements right until its correct place is found, then insert it.
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;
}
[5, 2, 9, 1].
- Insert 2: [2, 5, 9, 1].
- Insert 9: no shifts: [2, 5, 9, 1].
- Insert 1: shift 9, 5, 2: [1, 2, 5, 9].
Fast on nearly sorted data (few shifts); about $\frac{n^2}{2}$ comparisons in the worst case (reverse order).
Check yourself
Insertion sort is most efficient when the data is:
Show the answer
Already nearly sorted
Few shifts needed.
5Merge sort
Merge sort is a recursive divide-and-conquer algorithm: split the array in half, sort each half recursively, then merge the two sorted halves. It takes time proportional to $n \log n$, much faster than selection or insertion sort for large $n$, but needs extra memory for merging. (You need to recognise it, not write it.)
Check yourself
Merge sort works by:
Show the answer
Recursively sorting halves and merging them
Divide and conquer.
6Going deeper: tracing each algorithm and counting the work
Linear (sequential) search: check each element in turn.
- Works on any array, sorted or not.
- Worst case: n comparisons. Average for a present item: about n ÷ 2.
Binary search: repeatedly halve the range.
- Requires the data to be sorted.
- Compare the target with the middle element; discard the half that cannot contain it.
- Worst case: about log₂ n comparisons. For 1000 elements, about 10; for 1,000,000, about 20.
int low = 0;
int high = arr.length - 1;
while (low <= high) {
int mid = (low + high) / 2;
if (arr[mid] == target) {
return mid;
} else if (arr[mid] < target) {
low = mid + 1;
} else {
high = mid - 1;
}
}
return -1;
Worked example (binary search trace): search for 23 in {2, 5, 8, 12, 16, 23, 38, 56, 72} (indices 0 to 8).
- low = 0, high = 8, mid = 4: arr[4] = 16 is less than 23. low = 5.
- low = 5, high = 8, mid = 6: arr[6] = 38 is greater. high = 5.
- low = 5, high = 5, mid = 5: arr[5] = 23. Found at index 5, after 3 comparisons.
- Searching for 24 would continue: low = 6, high = 5; the loop ends and −1 is returned.
Selection sort: repeatedly select the smallest remaining element and swap it into place.
for (int i = 0; i < arr.length - 1; i++) {
int minIndex = i;
for (int j = i + 1; j < arr.length; j++) {
if (arr[j] < arr[minIndex]) {
minIndex = j;
}
}
int temp = arr[i];
arr[i] = arr[minIndex];
arr[minIndex] = temp;
}
Worked example (selection sort on {5, 2, 8, 1}):
- Pass 1: smallest is 1; swap with 5: {1, 2, 8, 5}.
- Pass 2: smallest of the rest is 2, already in place: {1, 2, 8, 5}.
- Pass 3: smallest of the rest is 5; swap with 8: {1, 2, 5, 8}.
After pass k, the first k elements are in their final positions.
Insertion sort: take each element in turn and insert it into the sorted portion to its left, shifting larger elements right.
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;
}
Worked example (insertion sort on {5, 2, 8, 1}):
- Insert 2: {2, 5, 8, 1}.
- Insert 8: already in place: {2, 5, 8, 1}.
- Insert 1: shifts 8, 5 and 2 right: {1, 2, 5, 8}.
After pass k, the first k + 1 elements are sorted among themselves, but not necessarily in final position.
Telling them apart from a snapshot: after two passes on {5, 2, 8, 1}, selection sort gives {1, 2, 8, 5} (the two smallest are in final position); insertion sort gives {2, 5, 8, 1} (the first three are in order, but 1 has yet to move).
Merge sort: divide the array in half, sort each half recursively, then merge the two sorted halves.
- Merging walks along both halves, repeatedly taking the smaller front element.
- {5, 2, 8, 1} → {5, 2} and {8, 1} → {2, 5} and {1, 8} → merge → {1, 2, 5, 8}.
- It needs extra space for a temporary array.
How much work?
- Selection sort: always about n² ÷ 2 comparisons, whatever the starting order; at most n − 1 swaps.
- Insertion sort: about n² ÷ 4 on average; only n − 1 comparisons if the data are already sorted (its best case); worst when the data are in reverse order.
- Merge sort: about n log₂ n, in every case. For 1000 elements, roughly 10,000 steps against roughly 500,000 for selection sort.
Statement counts: the exam may ask how many times a comparison or swap executes. For selection sort on 5 elements, the comparison runs 4 + 3 + 2 + 1 = 10 times.
Choosing a search: one search in unsorted data: linear. Many searches: sort once, then use binary search.
Common mistakes
- Using binary search on unsorted data.
low < highin place oflow <= high(misses a single remaining element).low = midorhigh = mid, which can loop forever.- Confusing selection and insertion sort snapshots.
- Saying insertion sort always takes the same time.
- Forgetting the base case in merge sort (a one-element array is already sorted).
Check yourself
What is the maximum number of comparisons binary search needs to find a value in a sorted array of 1000 elements?
Show the answer
About 10
Each comparison halves the range, and 2¹⁰ is 1024.
7For top marks
- Trace sorts pass by pass, writing the array after each pass.
- Selection sort: one swap per pass; insertion sort: many shifts per pass.
- Binary search: track
low,highandmidin a table; remember integer division inmid. - Compare efficiency: linear $n$, binary $\log_2 n$, selection/insertion $n^2$, merge $n \log n$.
for 64 sorted items, binary search needs at most 7 comparisons ($2^6 = 64$, plus the final check).
Check yourself
Which algorithm is fastest for searching a large sorted array?
Show the answer
Binary search
log₂ n.
Now test yourself
This lesson has a 8-question quiz and 5 exam-style questions with mark schemes in Impera. Free, with your progress saved.
Practise in Impera