GATE / CS ARCHIVE

GATE CSE 1999 / QUESTION 2.24

Recursive median function and ties

Programming in C · Recursion · Full GATE CSE 1999 paper

GATE 1999, Q2.24 2 marks · MSQ
Report issue

Recursion

Question 2.24, GATE 1999: Trial(a,b,c) returns b if a≥b and c<b; otherwise calls Trial(a,c,b) if a≥b, or Trial(b,a,c). Does it find maximum,minimum,median,or none?
Question 2.24, GATE 1999: Trial(a,b,c) returns b if a≥b and c<b; otherwise calls Trial(a,c,b) if a≥b, or Trial(b,a,c). Does it find maximum,minimum,median,or none?
Tap to enlarge
Select all that apply
Answer & solution

Answer: C on distinct values; not total for arbitrary integers (no official key was published)

For distinct values, a return requires c<b≤a, so b is the median. If a<b, swapping the first two puts the larger first. If a≥b but c≥b, swapping b and c either puts the middle value second or is followed by a first-pair swap; direct enumeration of the six strict orderings confirms termination at the median. Ties expose a defect: Trial(2,1,1) repeatedly calls itself because c<b is false while swapping equal arguments changes nothing. Trial(1,1,1) likewise never returns. Thus C describes the intended distinct-input algorithm, but no unconditional median function is established by the stated unrestricted int signature.

Original paper, page 6