AP Computer Science Exam Question:
Consider the following Java code snippet that implements the selection sort algorithm to sort an array in ascending order:
public class SelectionSort {
public static void selectionSort(int[] arr) {
int n = arr.length;
for (int i = 0; i < n-1; i++) {
int minIndex = i;
for (int j = i+1; j < n; j++) {
if (arr[j] < arr[minIndex]) {
minIndex = j;
}
}
int temp = arr[minIndex];
arr[minIndex] = arr[i];
arr[i] = temp;
}
}
public static void main(String[] args) {
int[] nums = {5, 2, 8, 1, 9};
selectionSort(nums);
for (int num : nums) {
System.out.print(num + " ");
}
}
}
Explain the steps involved in the selection sort algorithm and analyze the output of the above code snippet.
Answer:
The selection sort algorithm is an in-place sorting algorithm that works by repeatedly finding the minimum element from the unsorted part of the array and swapping it with the first element of the unsorted part. This process is repeated for each element until the entire array is sorted.
The steps involved in the selection sort algorithm are as follows:
n
with the length of the array.n-1
.i
is the minimum element and assign minIndex = i
.i+1
to n-1
, compare each element with the current minimum element.arr[j]
) is found to be smaller than the current minimum element (arr[minIndex]
), update minIndex
to j
.arr[minIndex]
) with the first element of the unsorted part (arr[i]
).By executing the above code snippet, the output will be: 1 2 5 8 9
.
Explanation of the output:
selectionSort(nums)
is called, where nums = {5, 2, 8, 1, 9}
.i = 0
.1
as the minimum element and assigns minIndex = 3
.1
is swapped with the first element 5
: {1, 2, 8, 5, 9}
.{1, 2, 8, 5, 9}
.i = 1
, and the inner loop finds 2
as the minimum element. Since 2
is already at the correct position, no swapping occurs.{1, 2, 8, 5, 9}
.5
, 8
, and 9
, respectively, but no swapping occurs as they are already at the correct positions.{1, 2, 5, 8, 9}
.Thus, the output of the above code is 1 2 5 8 9
.