Consider the following implementation of the selection sort algorithm in Java:
public class SelectionSort {
public static void selectionSort(int[] arr) {
int n = arr.length;
for (int i = 0; i < n-1; i++) {
int minIdx = i;
for (int j = i+1; j < n; j++) {
if (arr[j] < arr[minIdx]) {
minIdx = j;
}
}
int temp = arr[minIdx];
arr[minIdx] = arr[i];
arr[i] = temp;
}
}
public static void main(String[] args) {
int[] array = {5, 2, 7, 1, 3};
selectionSort(array);
for (int num : array) {
System.out.print(num + " ");
}
}
}
What will be the output of the main
method after executing the selectionSort
method on the array
array?
A) 1 2 3 5 7 B) 1 2 3 7 5 C) 5 2 7 1 3 D) 5 2 7 3 1
Explain the step-by-step process of how the selection sort algorithm sorts the given array.
The correct answer is A) 1 2 3 5 7.
Step-by-step process of how the selection sort algorithm sorts the given array:
Therefore, the output of the main
method after executing the selectionSort
method on the array
array will be "1 2 3 5 7" (option A).