Selection Sort Algorithm Stability
Consider the following selectionSort method. Is this implementation of the selection sort algorithm stable? Provide the correct explanation.
public class SelectionSortExample {
public static void selectionSort(int[] arr) {
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;
}
}
}
A
Yes, it is inherently stable since it compares only adjacent elements.
B
Yes, the algorithm is stable because it only swaps distinct elements.
C
No, the algorithm is not stable because swapping elements can change the relative order of equal elements.
D
No, but the stability can be achieved by modifying the inner loop to avoid unnecessary swaps.
Question Leaderboard
Not enough data yet to show leaderboard.
