Are you taking CLEP classes? Try clep.ai
| 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

Mark
< Prev
Next >

What is the output when the main method of the following InsertionSortFaulty class is executed?

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

[4, 1, 2, 3]

B

[1, 2, 3, 4]

C

[3, 2, 1, 4]

D

[4, 3, 2, 1]

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.

AI Tutor

How can I help?

APFIVE © 2020.
Email: apfive@apfive.org|Privacy Policy|