Selection Sort Algorithm Stability
Based on the above Selection Sort implementation, is the algorithm stable? Explain why.
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, the algorithm is stable because it only swaps distinct elements.
B
Yes, it is inherently stable since it compares only adjacent 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.
APFIVE