GATE / CS ARCHIVE

GATE CSE 1996 / QUESTION 18

Failure conditions of a binary search

Programming in C · Control Flow & Loop Tracing · Full GATE CSE 1996 paper

GATE 1996, Q18 5 marks · Descriptive
Report issue

Control Flow & Loop Tracing

Question 18, GATE 1996: For N>1, the following Pascal-like program searches an array a[1..N]: initialize i=1,j=N; repeatedly set k=floor((i+j)/2), then if a[k]<x set i=k, otherwise set j=k; stop when a[k]=x or i>=j. Finally print success if a[k]=x and failure otherwise. Determine when it fails. For the intended binary-search interpretation assume a is sorted in nondecreasing order. GFG prints the success message correctly; GateForum instead prints failure in both final branches.
Question 18, GATE 1996: For N>1, the following Pascal-like program searches an array a[1..N]: initialize i=1,j=N; repeatedly set k=floor((i+j)/2), then if a[k]<x set i=k, otherwise set j=k; stop when a[k]=x or i>=j. Finally print success if a[k]=x and failure otherwise. Determine when it fails. For the intended binary-search interpretation assume a is sorted in nondecreasing order. GFG prints the success message correctly; GateForum instead prints failure in both final branches.
Tap to enlarge
Answer & solution

Answer: It loops when x>a[1] and x is not in positions 1..N−1; in particular a unique match at the last element is missed (no official key was published)

The defect is that the lower update keeps the already examined element: i=k instead of i=k+1. When j=i+1, integer division gives k=i. If a[i]<x, setting i=k changes nothing; j also stays unchanged, a[k] is not x, and i<j remains true. The loop repeats forever.

In fact the final array position N is never examined: while i<j, floor((i+j)/2)<j<=N, so k<=N−1. On a nondecreasing array, the exact classification is: every x occurring among a[1],...,a[N−1] is eventually found; every x<a[1] terminates with failure; every x>a[1] absent from a[1..N−1] loops forever. The latter includes absent values between array entries, values above the maximum, and x=a[N] when that value occurs only at the last position. Duplicates matter: x=a[N] is found if the same value occurs earlier.

For example a=[1,3], x=3 gives (i,j,k)=(1,2,1) forever. With x=0, the first iteration instead sets j=1 and terminates correctly. For a=[1,3,5], x=3 is examined immediately and succeeds. These examples distinguish the actual bug from the inaccurate claim that all unsuccessful searches fail.

A robust repair uses while i<=j, tests equality first, then sets i=k+1 when a[k]<x and j=k−1 otherwise, reporting failure after the interval becomes empty. This also permits examining N.

Original paper, page 9