StreakPeaked· Practice

ExamsGATETechnical

Consider the C function given below. Assume that the array listA contains 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 ProcessArray is CORRECT?

  1. It will run into an infinite loop when x is not in listA.
  2. It is an implementation of binary search.
  3. It will always find the maximum element in listA.
  4. It will return -1 even when x is present in listA.

Correct answer: It is an implementation of binary search.

Solution

The function uses a divide-and-conquer approach to efficiently search for the element x within the sorted array listA, which is characteristic of binary search. It repeatedly narrows down the search range by comparing x with the middle element until it either finds x or determines that it is not present.

Related GATE Technical questions

⚔️ Practice GATE Technical free + battle 1v1 →