GATE / CS ARCHIVE

GATE CSE 2014 SET 3 / QUESTION 42

GATE CSE 2014 Set 3 Q42

Programming in C · Control Flow & Loop Tracing · Full GATE CSE 2014 Set 3 paper

GATE 2014 Set 3, Q42 2 marks · MCQ
Report issue

Control Flow & Loop Tracing

Question 42, GATE 2014: A sorted ascending array listA has n>0 entries. ProcessArray sets i=0,j=n−1, then repeatedly sets k=(i+j)/2 using integer division; if x≤listA[k], sets j=k−1; independently, if listA[k]≤x, sets i=k+1; repeats while i≤j. Afterward returns k if listA[k]==x, else −1. Which is correct? A absent x causes an infinite loop; B this is binary search; C it always finds the maximum; D it returns −1 even when x is present.
Tap to enlarge
Your answer
Answer & solution

Official answer: B

Step 1: If x is smaller than the midpoint, only the first comparison succeeds, eliminating the midpoint and upper half. If x is larger, only the second succeeds, eliminating the lower half. Each unsuccessful iteration strictly shrinks the candidate interval. Step 2: If x equals the midpoint, both independent tests succeed: j=k−1 and i=k+1. The loop terminates immediately, and the final equality test returns the matching k. Step 3: Therefore it implements binary search, B, including for duplicates where any matching index suffices. Assume a valid nonempty sorted array and arithmetic without overflow in i+j.

Original paper, page 63 · Answer key