GATE Computer ScienceHardGATE CS

The standard next_permutation algorithm (find the rightmost i with a[i] < a[i+1], swap a[i] with the rightmost larger a[j] to its right, then reverse the suffix after i) is applied 5 times in succession to [2, 4, 3, 1, 5]. What is the array afterwards?

  1. A. [2, 5, 3, 1, 4]
  2. B. [2, 4, 5, 3, 1]
  3. C. [2, 5, 1, 3, 4]
  4. D. [2, 5, 1, 4, 3]

Correct answer: D. [2, 5, 1, 4, 3]

The successive results are [2,4,3,5,1], [2,4,5,1,3], [2,4,5,3,1], [2,5,1,3,4] and finally [2,5,1,4,3]. Each result is the next arrangement in lexicographic order.

More Programming and Data Structures (GATE) questions

Exams that ask this topic