Skip to content
Official PYQ · 2014

GATE CS 2014 Set 3 Q42 — Arrays, Stacks and Queues

Explain with AI

Consider the C function given below. Assume that the array listAlistA contains n(>0)n (>0) elements, sorted in ascending order.

int ProcessArray(int *listA, int x, int n)   
{     
        int i, j, k;     
        i = 0;     j = n-1;     
         do { 
               k = (i+j)/2;         
               if (x <= listA[k]) j = k-1;         
               if (listA[k] <= x) i = k+1; 
             }
        while (i <= j);     
        if (listA[k] == x) return(k);     
        else   return -1;   
}     

Which one of the following statements about the function ProcessArrayProcessArray is CORRECT?

Choose one option
View worked solution

Answer: B

The given function is an implementation of the binary search algorithm on a sorted array. Let's trace how the search space is updated in each iteration of the loop:

  • Case 1: x<listA[k]x < listA[k]
    Only the first condition x <= listA[k] is satisfied. Thus, j is updated to k - 1, narrowing the search to the left half.
  • Case 2: x>listA[k]x > listA[k]
    Only the second condition listA[k] <= x is satisfied. Thus, i is updated to k + 1, narrowing the search to the right half.
  • Case 3: x==listA[k]x == listA[k]
    Both conditions are satisfied. Thus, j becomes k - 1 and i becomes k + 1. This makes i > j, causing the loop condition i <= j to fail. The loop terminates, and the function correctly returns the index k because listA[k] == x holds true.

Since the search space [i, j] strictly shrinks in every iteration, the loop is guaranteed to terminate. Thus, the function is a valid implementation of binary search.

Free practice · Your answers on this page are not saved.

Published
Report a correction
Keep exploringMore Arrays, Stacks and Queues questions