GATE Computer ScienceVery hardGATE CS (PYQ pattern)

void insert(Stack *s, int x) { if (empty(s) || top(s) <= x) { push(s, x); return; } int y = pop(s); insert(s, x); push(s, y); } void sort(Stack *s) { if (!empty(s)) { int x = pop(s); sort(s); insert(s, x); } } The stack holds (bottom to top) 3, 7, 1, 9, 4, 8. How many calls to insert (including recursive ones) are made while sort runs?

  1. A. 9
  2. B. 14
  3. C. 11
  4. D. 15

Correct answer: C. 11

sort pops from the top (8, 4, 9, 1, 7, 3 in turn) and inserts them back in reverse order into an already-sorted stack. Each insert makes 1 + (number of elements on the stack greater than x) calls; summing over the six insertions gives 11.

More Programming and Data Structures (GATE) questions

Exams that ask this topic