158 views
3 votes
3 votes

Consider the code given below, which runs insertion sort:

void insertionSort(int arr[], int size)
{
    int i, j, value;
    for (i = 1; i < size; i++)
    {
        value = arr[i];
        j = i;
        while (________ )
        {
            arr[j] = arr[j - 1];
            j = j - 1;
        }
        arr[j] = value;
    }
}


Which condition will correctly implement the while loop?

  1. $(j > 0) \ || \ (arr[j - 1] > value)$
  2. $(j > 0) \ \&\& \ (arr[j - 1] > value)$
  3. $(j > 0) \ \&\& \ (arr[j + 1] > value)$
  4. $(j > 0) \ \&\& \ (arr[j + 1] < value)$

 

1 Answer

0 votes
0 votes
for (j =2 to array.length)

     key = array[j];

     i =j-1;

     while(i > 0 && array[i] > key)

             array[i+1] = array[i];

             i = i-1;

array[i+1]= key;

 

above is the standard algorithm of insertion sort, from this we can easily infer that  (j>0) && (arr[j−1]>value) is the right option.

 

Hence, B is right answer.
Answer:

Related questions