Skip to content
Related Articles
Open in App
Not now

Related Articles

GATE | GATE CS 1996 | Question 66

Improve Article
Save Article
  • Difficulty Level : Hard
  • Last Updated : 24 Mar, 2019
Improve Article
Save Article

Consider the following program that attempts to locate an element x in a sorted array a[ ] using binary search. Assume N>1. The program is erroneous. Under what conditions does the program fail?

var i,j,k: integer;  x: integer;
    a: array; [1....N] of integer;
begin    i:= 1; j:= N;
    k:(i+j) div 2;
    if a[k] < x then i:= k 
    else j:= k 
until (a[k] = x) or (i >= j);
if (a[k] = x) then
    writeln ('x is in the array')
    writeln ('x is not in the array')

(A) x is the last element of the array a[]
(B) x is greater than all elements of the array a[]
(C) Both of the Above
(D) x is less than the last element of the array a[]

Answer: (C)

Explanation: The above program doesn’t work for the cases where element to be searched is the last element of a[] or greater than the last element (or maximum element) in a[]. For such cases, program goes in an infinite loop because i is assigned value as k in all iterations, and i never becomes equal to or greater than j. So while condition never becomes false.

Quiz of this Question

My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!