3.2k views

Suppose we want to arrange the $n$ 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

1. $n-1$
2. $n$
3. $n+1$
4. None of the above
+2
Logic is similar to Quick sort partition method.
0

Chhotu by that way (partition method) it wont take minimum exchanges.

Answer is (D) None of these.

We just require $n/2$ swaps in the worst case. The algorithm is as given below:

Find positive number from left side and negative number from right side and do exchange. Since, at least one of them must be less than or equal to $n/2$, there cannot be more than $n/2$ exchanges. An implementation is given below:

http://gatecse.in/wiki/Moving_Negative_Numbers_to_the_Beginning_of_Array

edited
+1

can I use simple selection sort instead ? coz it will too lead to a minimum of n/2 exchange.

0
Is the meaning of exchange and swapping is same?
+1

yes @srestha

0
@Arjun Sir what if the array contains negative elements on the first few and last few positions, We can not simply swap them. What to do in this case.

Let Array be,

A [10 -25 -5 -95 -22- 45 12 45 12 87 45 12 45 87 65 31 05 85 -12 -23 -45 -89 -65 -32]
Please Let me know how it can be solved in n/2.
it would be n-1 in a worst case, n is never the case because if all are -ve number then there is no exchange. But in worst case array is like 1,-1,-2,-3,-4.... so total n-1 exchange are needed.
0
Why this answer is marked wrong?? I think n-1 is worst case as compared to n/2 as n-1 will always take more time. If we look asymptotically it's O(n). Please explain I am confused
0
I thought in the same way

My view : suppose we are given n numbers atored in array. We can use quick sort as in worst case it can arrange all the elements in array in( log n) time.. Run quick sort algo. On Given number and check how many times the swap() function is called in quick sort algo... So count of swap() function in quick sort algo is our minimum no of exchange required to arrange all elemnts in the given array!!! Correct me if wrong. Plzz
0
but the option is      n     n-1       n+1        n(n+1)/2

then which of the option is correct
0
quick sort best case time complexity nlogn
0
What if we apply merge sort?