| preferred AP College board partner for AP classes
AP Computer Science A/Unit 6: Array
Start Practice TestPractice Test
About Exam
hard Solved by 2 students
Selection Sort Algorithm Stability
< Prev
Next >

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.

Hint
Did You Know?
Explain Why
Explain All Answers
Check Answer
Show Correct Answer
Report Question

Question Leaderboard

Not enough data yet to show leaderboard.

No comments yet. Be the first to comment!

AI Tutor

How can I help?

APFIVE © 2020.
Email: [email protected]|Privacy Policy