Selection Sort
Solution
public static void selectionSort(int[] arr) {
for (int end = arr.length - 1; end > 0; end--) {
int maxIndex = 0;
for (int j = 1; j <= end; j++) {
if (arr[j] > arr[maxIndex]) {
maxIndex = j;
}
}
int temp = arr[end];
arr[end] = arr[maxIndex];
arr[maxIndex] = temp;
}
}
Solution
, on every input. The inner scan cannot stop early: it does not know it has found the largest element until it has looked at every element, so the values never change how many comparisons happen.
Solution
Sorted: . Reverse sorted: about , since each swap puts two elements in their final places. Largest possible: , one per pass. [2, 3, 4, 5, 1] reaches it: each pass swaps the 1 one slot to the left.
Solution
At most swaps, so writes to the array. It is the right choice when writing an element is expensive and comparing two is cheap, since its comparisons are still .