144k views
4 votes
Consider the following correct implementation of the insertion sort algorithm.public static void insertionSort(int[] elements){for (int j = 1; j < elements.length; j++){int temp = elements[j];int possibleIndex = j;while (possibleIndex > 0 && temp < elements[possibleIndex - 1]){elements[possibleIndex] = elements[possibleIndex - 1];possibleIndex--; // line 10}elements[possibleIndex] = temp;}}The following declaration and method call appear in a method in the same class as insertionSort.int[] arr = {10, 8, 3, 4};insertionSort(arr);How many times is the statement possibleIndex--; in line 10 of the method executed as a result of the call to insertionSort ?A) 1B) 2C) 3D) 4E) 5

User Mydoglixu
by
6.6k points

1 Answer

0 votes

Answer: The answer is C) 3.

Explanation: The statement possibleIndex--; in line 10 of the insertionSort method is executed each time the while loop condition is true. Specifically, it is executed each time the following two conditions are met:

i) The value of possibleIndex is greater than 0.

ii) The value of the temporary variable temp is less than the element at index possibleIndex - 1.

For the given array {10, 8, 3, 4}, the while loop will be executed for each element from index 1 to index 3, because those are the only elements that are smaller than the element to their left. Therefore, the statement possibleIndex--; will be executed 3 times (once for each of these elements).

User Angelino
by
7.3k points