GATE Computer ScienceVery hardGATE CS (PYQ pattern)

Dutch-national-flag partition on a = [2, 0, 1, 2, 1, 0, 0, 2, 1, 1, 0, 2]: lo = mid = 0, hi = 11; while mid <= hi: if a[mid] == 0 { swap(a[lo], a[mid]); lo++; mid++; } else if a[mid] == 1 mid++; else { swap(a[mid], a[hi]); hi--; }. How many swap calls are made, and in how many of them are the two values exchanged actually different?

  1. A. 8 calls, 8 effective
  2. B. 8 calls, 4 effective
  3. C. 8 calls, 5 effective
  4. D. 7 calls, 5 effective

Correct answer: C. 8 calls, 5 effective

Trace: mid = 0 holds 2 and is swapped with a[11] = 2 (equal values); the new a[0] is again 2 and is swapped with a[10] = 0; then mid = 0 and mid = 1 hold 0 while lo == mid, so those swaps exchange an element with itself; later 2 <-> 1 at (3, 9), 1 <-> 0 at (2, 5) and (3, 6), and 2 <-> 1 at (7, 8). That is 8 swap calls (one per 0 and per 2, as expected), but 3 of them exchange equal values, leaving 5 that actually move data.

More Programming and Data Structures (GATE) questions

Exams that ask this topic