Data Structures & AlgorithmsHardTCS NQT · GATE CS

Using swaps of ADJACENT elements only, what is the minimum number of swaps needed to sort the binary array [1, 0, 1, 1, 0, 0, 1, 0] so that all 0s come before all 1s?

  1. A. 11
  2. B. 13
  3. C. 4
  4. D. 5

Correct answer: A. 11

Each 0 must move past every 1 standing before it, and each such crossing is one adjacent swap; summing the number of 1s before each 0 gives the total. Counting the misplaced ones (or the zeros) gives a much smaller number, which is the usual slip.

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

Exams that ask this topic