Codeforces celebrates 10 years! We are pleased to announce the crowdfunding-campaign. Congratulate us by the link https://codeforces.com/10years. ×

### wish_me's blog

By wish_me, history, 2 years ago, , An array contains both positive and negative numbers in random order. Rearrange the array elements so that positive and negative numbers are placed alternatively. Number of positive and negative numbers need not be equal. If there are more positive numbers they appear at the end of the array. If there are more negative numbers, they too appear in the end of the array.

For example, if the input array is [-1, 2, -3, 4, 5, 6, -7, 8, 9], then the output should be [2,-1,4,-3,5,-7,6,8,9]

array size < 10^3 Comments (2)
 » Ok so we have 2 cases depending on whether there are more negative numbers or vice-versa. Once we separate the negative numbers on the left side and the positive ones on the right side, it's easy to permute a prefix or suffix in O(1) by some swaps to get the array alternatively. Let K = the number of negative numbers. Start with a pointer, j, at K+1th position. Now start with i from 1 to K. If p[i] < 0 do nothing, otherwise increase j as long as p[j] > 0. You stop when P[j]<0 and then make a swap (p[i], p[j]). At the end of this process you'll have separated the negative numbers from the positive ones. Then you only need to permute a prefix or a suffix on the basis of some simple formulas
•  » » Well then the order of elements would not be same..