Skip to content
Official PYQ · 1999

GATE CS 1999 Q1.13 — Asymptotic Worst Case Time and Space Complexity

Explain with AI

Suppose we want to arrange the nn numbers stored in any array such that all negative values occur before all positive ones. Minimum number of exchanges required in the worst case is

Choose one option
View worked solution

Answer: D

To find the minimum number of exchanges required in the worst case to partition an array of nn numbers such that all negative values appear before all positive ones, we can analyze the problem as follows:

  1. Let n−n_- be the number of negative elements and n+n_+ be the number of positive elements in the array, so that n−+n+=nn_- + n_+ = n.
  2. In the partitioned array, the first n−n_- positions must contain all the negative elements, and the remaining n+n_+ positions must contain all the positive elements.
  3. Suppose there are kk positive elements currently located in the first n−n_- positions. This means there are exactly n−−kn_- - k negative elements in this region.
  4. Since the total number of negative elements is n−n_-, the number of negative elements located in the second region (the last n+n_+ positions) must be: n−−(n−−k)=kn_- - (n_- - k) = k
  5. To partition the array, we only need to swap each of the kk misplaced positive elements in the first region with a misplaced negative element in the second region. This requires exactly kk exchanges.
  6. The worst-case scenario occurs when the number of misplaced elements kk is maximized. Since k≤n−k \le n_- and k≤n+k \le n_+, we have: k≤min⁡(n−,n+)k \le \min(n_-, n_+)
  7. Subject to n−+n+=nn_- + n_+ = n, the maximum possible value of min⁡(n−,n+)\min(n_-, n_+) is ⌊n/2⌋\lfloor n/2 \rfloor.

Thus, the minimum number of exchanges required in the worst case is ⌊n/2⌋\lfloor n/2 \rfloor. Since this value is not represented by options A, B, or C, the correct option is D.

Free practice · Your answers on this page are not saved.

Published
Report a correction
Keep exploringMore Asymptotic Worst Case Time and Space Complexity questions