Complete the Selection sort practice problem before viewing the solution.

Review the selection sort practice problem with AP CS Tutor Brandon Horn.

## Selection sort trace

[| 71 86 79 36 78 35 75 86 24 11] [11 | 86 79 36 78 35 75 86 24 71] [11 24 | 79 36 78 35 75 86 86 71] [11 24 35 | 36 78 79 75 86 86 71] [11 24 35 36 | 78 79 75 86 86 71] [11 24 35 36 71 | 79 75 86 86 78] [11 24 35 36 71 75 | 79 86 86 78] [11 24 35 36 71 75 78 | 86 86 79] [11 24 35 36 71 75 78 79 | 86 86] [11 24 35 36 71 75 78 79 86 | 86]

The elements to the left of the separator (|) are sorted and are in their final positions. The elements to the right of the separator are unchecked. The separator starts before the first element.

Note that once the elements from x[0] to x[x.length-2] have been placed in their final positions, x[x.length-1] must also be in its final position.

## Selection sort implementation

public static void sort(int[] x) { for (int i = 0; i < x.length - 1; i++) { int minIndex = i; for (int j = i + 1; j < x.length; j++) if (x[j] < x[minIndex]) minIndex = j; swap(x, i, minIndex); } } private static void swap(int[] x, int i, int j) { int temp = x[i]; x[i] = x[j]; x[j] = temp; }