Data Structures & AlgorithmsVery hardFlipkart/Uber OA · placement

The Dutch national flag algorithm (pointers low, mid, high; 0 → swap with low and advance both; 1 → advance mid; 2 → swap with high and decrement high only) sorts [1, 2, 0, 0, 0, 1, 1, 2, 0]. How many swaps does it perform (count every swap call, even a self-swap)?

  1. A. 5
  2. B. 6
  3. C. 7
  4. D. 9

Correct answer: B. 6

Every 0 and every 2 visited by mid causes one swap call; a 2 swapped in from the back is re-examined. Tracing gives 6 swap calls.

More Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questions

Exams that ask this topic