Insertion Sort Loop Condition Error
The following insertionSort method is intended to sort an array of integers but contains a logical error. Which statement best describes the error?
public class InsertionSortError {
public static void insertionSort(int[] arr) {
for (int i = 1; i < arr.length; i++) {
int key = arr[i];
int j = i - 1;
while(j > 0 && arr[j] > key) {
arr[j+1] = arr[j];
j--;
}
arr[j+1] = key;
}
}
}
A
The key should be stored as a float for better precision.
B
The for-loop should start at i = 0 instead of i = 1.
C
Elements should be shifted to the left rather than to the right.
D
The while loop condition should be ‘j >= 0’ instead of ‘j > 0’, to ensure the first element is compared.
Question Leaderboard
| Rank | |||||
|---|---|---|---|---|---|
| #1 | ngvandangthanh | 1 | 1 | - | 100 |
| #2 | sfsdfdsfsd | 1 | 1 | 0m 01s | 99 |
| #3 | Potter16 | 1 | 1 | 0m 31s | 69 |
| #4 | bommasam000 | 1 | 2 | 1m 13s | 17 |
| #5 | sssemihunal | 0 | 1 | 0m 01s | -11 |
| #6 | lsj08030922 | 1 | 2 | 2m 43s | -73 |
| #7 | parth.taur227 | 1 | 1 | 7m 44s | -364 |
| #8 | jeonsaw1723 | 1 | 4 | 24m 16s | -1,386 |
Items per page:
10
1 – 8 of 8
