Insertion Sort Loop Boundary Error
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]
Question Leaderboard
Not enough data yet to show leaderboard.
APFIVE