| preferred AP College board partner for AP classes
AP Computer Science A/Unit 4: Iteration
Start Practice TestPractice Test
About Exam
hard
Insertion Sort Loop Boundary Error
< Prev
Next >

What output does the above faulty insertion sort code produce?

public class InsertionSortFaulty {
    public static void insertionSort(int[] arr) {
         for (int i = 1; i < arr.length; i++) {
             int key = arr[i];
             int j = i - 1;
             // Incorrect condition: should be j >= 0 but uses j > 0
             while(j > 0 && arr[j] > key) {
                 arr[j+1] = arr[j];
                 j--;
             }
             arr[j+1] = key;
         }
         System.out.println(java.util.Arrays.toString(arr));
    }
    
    public static void main(String[] args) {
         int[] numbers = {4, 3, 2, 1};
         insertionSort(numbers);
    }
}
A

[1, 2, 3, 4]

B

[3, 2, 1, 4]

C

[4, 3, 2, 1]

D

[4, 1, 2, 3]

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