VOOZH about

URL: https://www.geeksforgeeks.org/dsa/rearrange-positive-and-negative-numbers-publish/

⇱ Alternate Rearrangement of Positives and Negatives - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Alternate Rearrangement of Positives and Negatives

Last Updated : 23 Jul, 2025

An array contains both positive and negative numbers in random order. Rearrange the array elements so that positive and negative numbers are placed alternatively. A 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 at the end of the array.

Example:

Input: [-1, 2, -3, 4, 5, 6, -7, 8, 9]
Output: [9, -7, 8, -3, 5, -1, 2, 4, 6]

Input: [-1, 3, -2, -4, 7, -5]
Output: [7, -2, 3, -5, -1, -4]


Note: The partition process in this approach changes the relative order of elements. I.e. the order of the appearance of elements is not maintained with this approach. See this for maintaining the order of appearance of elements in this problem.

Approach:

The solution is to first separate positive and negative numbers using the partition process of QuickSort. In the partition process, consider 0 as the value of the pivot element so that all negative numbers are placed before positive numbers. Once negative and positive numbers are separated, we start from the first negative number and first positive number and swap every alternate negative number with the next positive number. 

Below is the implementation of above idea:


Output
5 -5 2 -2 4 -8 7 1 8 0 


Time Complexity: O(n) where n is number of elements in given array. As, we are using a loop to traverse N times so it will cost us O(N) time 
Auxiliary Space: O(n)


Related Articles:
Rearrange positive and negative numbers with constant extra space
Move all negative elements to end in order with extra space allowed

Comment
Article Tags: