GFG App
Open App
Browser
Continue

# Rearrange positive and negative numbers in O(n) time and O(1) extra space

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.
For example, if the input array is [-1, 2, -3, 4, 5, 6, -7, 8, 9], then the output should be [9, -7, 8, -3, 5, -1, 2, 4, 6]
Note: The partition process 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.
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.

Flowchart

Flowchart of below code

## C++

 `// A C++ program to put positive` `// numbers at even indexes (0, 2, 4,..) ` `// and negative numbers at odd ` `// indexes (1, 3, 5, ..)` `#include ` `using` `namespace` `std;`   `class` `GFG` `{` `    ``public``:` `    ``void` `rearrange(``int` `[],``int``);` `    ``void` `swap(``int` `*,``int` `*);` `    ``void` `printArray(``int` `[],``int``);` `};`   `// The main function that rearranges ` `// elements of given array. It puts` `// positive elements at even indexes ` `// (0, 2, ..) and negative numbers ` `// at odd indexes (1, 3, ..).` `void` `GFG :: rearrange(``int` `arr[], ``int` `n)` `{` `    ``// The following few lines are ` `    ``// similar to partition process` `    ``// of QuickSort. The idea is to ` `    ``// consider 0 as pivot and` `    ``// divide the array around it.` `    ``int` `i = -1;` `    ``for` `(``int` `j = 0; j < n; j++)` `    ``{` `        ``if` `(arr[j] < 0)` `        ``{` `            ``i++;` `            ``swap(&arr[i], &arr[j]);` `        ``}` `    ``}`   `    ``// Now all positive numbers are at ` `    ``// end and negative numbers at the` `    ``// beginning of array. Initialize ` `    ``// indexes for starting point of` `    ``// positive and negative numbers ` `    ``// to be swapped` `    ``int` `pos = i + 1, neg = 0;`   `    ``// Increment the negative index by ` `    ``// 2 and positive index by 1,` `    ``// i.e., swap every alternate negative ` `    ``// number with next positive number` `    ``while` `(pos < n && neg < pos && ` `                     ``arr[neg] < 0)` `    ``{` `        ``swap(&arr[neg], &arr[pos]);` `        ``pos++;` `        ``neg += 2;` `    ``}` `}`   `// A utility function ` `// to swap two elements` `void` `GFG :: swap(``int` `*a, ``int` `*b)` `{` `    ``int` `temp = *a;` `    ``*a = *b;` `    ``*b = temp;` `}`   `// A utility function to print an array` `void` `GFG :: printArray(``int` `arr[], ``int` `n)` `{` `    ``for` `(``int` `i = 0; i < n; i++)` `        ``cout << arr[i] << ``" "``;` `}`   `// Driver Code` `int` `main() ` `{` `    ``int` `arr[] = {-1, 2, -3, 4, ` `                  ``5, 6, -7, 8, 9};` `    ``int` `n = ``sizeof``(arr) / ``sizeof``(arr[0]);` `    ``GFG test;` `    ``test.rearrange(arr, n);` `    ``test.printArray(arr, n);` `    ``return` `0;` `}`   `// This code is contributed ` `// by vt_Yogesh Shukla 1`

## C

 `// A C++ program to put positive numbers at even indexes (0, ` `// 2, 4,..) and negative numbers at odd indexes (1, 3, 5, ..)` `#include `   `// prototype for swap` `void` `swap(``int` `*a, ``int` `*b);`   `// The main function that rearranges elements of given array. ` `// It puts  positive elements at even indexes (0, 2, ..) and ` `// negative numbers at odd indexes (1, 3, ..).` `void` `rearrange(``int` `arr[], ``int` `n)` `{` `    ``// The following few lines are similar to partition process` `    ``// of QuickSort.  The idea is to consider 0 as pivot and` `    ``// divide the array around it.` `    ``int` `i = -1;` `    ``for` `(``int` `j = 0; j < n; j++)` `    ``{` `        ``if` `(arr[j] < 0)` `        ``{` `            ``i++;` `            ``swap(&arr[i], &arr[j]);` `        ``}` `    ``}`   `    ``// Now all positive numbers are at end and negative numbers` `    ``// at the beginning of array. Initialize indexes for starting` `    ``// point of positive and negative numbers to be swapped` `    ``int` `pos = i+1, neg = 0;`   `    ``// Increment the negative index by 2 and positive index by 1,` `    ``// i.e., swap every alternate negative number with next ` `    ``// positive number` `    ``while` `(pos < n && neg < pos && arr[neg] < 0)` `    ``{` `        ``swap(&arr[neg], &arr[pos]);` `        ``pos++;` `        ``neg += 2;` `    ``}` `}`   `// A utility function to swap two elements` `void` `swap(``int` `*a, ``int` `*b)` `{` `    ``int` `temp = *a;` `    ``*a = *b;` `    ``*b = temp;` `}`   `// A utility function to print an array` `void` `printArray(``int` `arr[], ``int` `n)` `{` `    ``for` `(``int` `i = 0; i < n; i++)` `        ``printf``(``"%4d "``, arr[i]);` `}`   `// Driver program to test above functions` `int` `main()` `{` `    ``int` `arr[] = {-1, 2, -3, 4, 5, 6, -7, 8, 9};` `    ``int` `n = ``sizeof``(arr)/``sizeof``(arr[0]);` `    ``rearrange(arr, n);` `    ``printArray(arr, n);` `    ``return` `0;` `}`

## Java

 `// A JAVA program to put positive numbers at even indexes` `// (0, 2, 4,..) and negative numbers at odd indexes (1, 3,` `// 5, ..)` `import` `java.io.*;`   `class` `Alternate {`   `    ``// The main function that rearranges elements of given` `    ``// array.  It puts positive elements at even indexes (0,` `    ``// 2, ..) and negative numbers at odd indexes (1, 3, ..).` `    ``static` `void` `rearrange(``int` `arr[], ``int` `n)` `    ``{` `        ``// The following few lines are similar to partition` `        ``// process of QuickSort.  The idea is to consider 0` `        ``// as pivot and divide the array around it.` `        ``int` `i = -``1``, temp = ``0``;` `        ``for` `(``int` `j = ``0``; j < n; j++)` `        ``{` `            ``if` `(arr[j] < ``0``)` `            ``{` `                ``i++;` `                ``temp = arr[i];` `                ``arr[i] = arr[j];` `                ``arr[j] = temp;` `            ``}` `        ``}`   `        ``// Now all positive numbers are at end and negative numbers at` `        ``// the beginning of array. Initialize indexes for starting point` `        ``// of positive and negative numbers to be swapped` `        ``int` `pos = i+``1``, neg = ``0``;`   `        ``// Increment the negative index by 2 and positive index by 1, i.e.,` `        ``// swap every alternate negative number with next positive number` `        ``while` `(pos < n && neg < pos && arr[neg] < ``0``)` `        ``{` `            ``temp = arr[neg];` `            ``arr[neg] = arr[pos];` `            ``arr[pos] = temp;` `            ``pos++;` `            ``neg += ``2``;` `        ``}` `    ``}`   `    ``// A utility function to print an array` `    ``static` `void` `printArray(``int` `arr[], ``int` `n)` `    ``{` `        ``for` `(``int` `i = ``0``; i < n; i++)` `            ``System.out.print(arr[i] + ``"   "``);` `    ``}`   `    ``/*Driver function to check for above functions*/` `    ``public` `static` `void` `main (String[] args)` `    ``{` `        ``int` `arr[] = {-``1``, ``2``, -``3``, ``4``, ``5``, ``6``, -``7``, ``8``, ``9``};` `        ``int` `n = arr.length;` `        ``rearrange(arr,n);` `        ``System.out.println(``"Array after rearranging: "``);` `        ``printArray(arr,n);` `    ``}` `}` `/*This code is contributed by Devesh Agrawal*/`

## Python3

 `#  Python program to put positive numbers at even indexes (0,  // 2, 4,..) and` `#  negative numbers at odd indexes (1, 3, 5, ..)`   `# The main function that rearranges elements of given array. ` `# It puts  positive elements at even indexes (0, 2, ..) and ` `# negative numbers at odd indexes (1, 3, ..).` `def` `rearrange(arr, n):` `    ``# The following few lines are similar to partition process` `    ``# of QuickSort.  The idea is to consider 0 as pivot and` `    ``# divide the array around it.` `    ``i ``=` `-``1` `    ``for` `j ``in` `range``(n):` `        ``if` `(arr[j] < ``0``):` `            ``i ``+``=` `1` `            ``# swapping of arr` `            ``arr[i], arr[j] ``=` `arr[j], arr[i]` ` `  `    ``# Now all positive numbers are at end and negative numbers` `    ``# at the beginning of array. Initialize indexes for starting` `    ``# point of positive and negative numbers to be swapped` `    ``pos, neg ``=` `i``+``1``, ``0` ` `  `    ``# Increment the negative index by 2 and positive index by 1,` `    ``# i.e., swap every alternate negative number with next ` `    ``# positive number` `    ``while` `(pos < n ``and` `neg < pos ``and` `arr[neg] < ``0``):`   `        ``# swapping of arr` `        ``arr[neg], arr[pos] ``=` `arr[pos], arr[neg]` `        ``pos ``+``=` `1` `        ``neg ``+``=` `2`   `# A utility function to print an array` `def` `printArray(arr, n):` `    `  `    ``for` `i ``in` `range``(n):` `        ``print` `(arr[i],end``=``" "``)` ` `  `# Driver program to test above functions` `arr ``=` `[``-``1``, ``2``, ``-``3``, ``4``, ``5``, ``6``, ``-``7``, ``8``, ``9``]` `n ``=` `len``(arr)` `rearrange(arr, n)` `printArray(arr, n)`   `# Contributed by Afzal`

## C#

 `// A C# program to put positive numbers` `// at even indexes (0, 2, 4, ..) and ` `// negative numbers at odd indexes (1, 3, 5, ..)` `using` `System;`   `class` `Alternate {`   `    ``// The main function that rearranges elements ` `    ``// of given array. It puts positive elements ` `    ``// at even indexes (0, 2, ..) and negative ` `    ``// numbers at odd indexes (1, 3, ..).` `    ``static` `void` `rearrange(``int``[] arr, ``int` `n)` `    ``{` `        ``// The following few lines are similar to partition` `        ``// process of QuickSort. The idea is to consider 0` `        ``// as pivot and divide the array around it.` `        ``int` `i = -1, temp = 0;` `        ``for` `(``int` `j = 0; j < n; j++) {` `            ``if` `(arr[j] < 0) {` `                ``i++;` `                ``temp = arr[i];` `                ``arr[i] = arr[j];` `                ``arr[j] = temp;` `            ``}` `        ``}`   `        ``// Now all positive numbers are at end ` `        ``// and negative numbers at the beginning of ` `        ``// array. Initialize indexes for starting point` `        ``// of positive and negative numbers to be swapped` `        ``int` `pos = i + 1, neg = 0;`   `        ``// Increment the negative index by 2 and` `        ``// positive index by 1, i.e., swap every ` `        ``// alternate negative number with next positive number` `        ``while` `(pos < n && neg < pos && arr[neg] < 0) {` `            ``temp = arr[neg];` `            ``arr[neg] = arr[pos];` `            ``arr[pos] = temp;` `            ``pos++;` `            ``neg += 2;` `        ``}` `    ``}`   `    ``// A utility function to print an array` `    ``static` `void` `printArray(``int``[] arr, ``int` `n)` `    ``{` `        ``for` `(``int` `i = 0; i < n; i++)` `            ``Console.Write(arr[i] + ``" "``);` `    ``}`   `    ``/*Driver function to check for above functions*/` `    ``public` `static` `void` `Main()` `    ``{` `        ``int``[] arr = { -1, 2, -3, 4, 5, 6, -7, 8, 9 };` `        ``int` `n = arr.Length;` `        ``rearrange(arr, n);` `        ``printArray(arr, n);` `    ``}` `}`   `// This code is contributed by vt_m.`

## PHP

 ``

## Javascript

 ``

Output:

`    4   -3    5   -1    6   -7    2    8    9`

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(1), as we are not using any extra space.

New Approach:- This approach uses two pointers, i and j, that start at opposite ends of the array. The pointer i moves forward to find the next negative element, while the pointer j moves backward to find the next positive element. When both i and j have found an element that is out of place, they swap positions. This process continues until i and j cross, at which point all elements have been rearranged.

This approach only requires O(1) extra space because it rearranges the elements in place, without creating a separate copy of the array.

Steps:-

1. The code defines a class called Alternate.
2. The rearrange() method takes an integer array and its length as input parameters.
3. Two variables i and j are initialized to -1 and n, respectively.
4. The while loop executes infinitely until it returns from inside the loop.
5. In the first inner while loop, the value of i is incremented until a negative element is encountered.
6. In the second inner while loop, the value of j is decremented until a positive element is encountered.
7. If i and j cross each other, the rearrangement of all elements is complete and the function returns.
8. If i and j have not crossed each other, the positive and negative elements are swapped.
9. The printArray() method takes an integer array and its length as input parameters.
10. A for loop is used to iterate through the array elements and print them.
11. If the current iteration index modulo 3 is equal to 0, a newline character is printed to break the line.
12. The main() method creates an integer array with some initial values, calls the rearrange() method to rearrange its elements, and then calls the printArray() method to print the rearranged array with every third element on a new line.

Below is the implementation of the above approach:

## C++

 `#include ` `using` `namespace` `std;`   `void` `rearrange(``int` `arr[], ``int` `n)` `{` `    ``int` `i = -1, j = n;` `    ``while` `(``true``) {` `        ``// Move i to the next negative element` `        ``while` `(i < n - 1 && arr[++i] >= 0) {` `        ``}` `        ``// Move j to the next positive element` `        ``while` `(j > 0 && arr[--j] < 0) {` `        ``}`   `        ``// If i and j cross, we have rearranged all elements` `        ``if` `(i >= j) {` `            ``return``;` `        ``}`   `        ``// Swap the positive and negative elements` `        ``int` `temp = arr[i];` `        ``arr[i] = arr[j];` `        ``arr[j] = temp;` `    ``}` `}`   `void` `printArray(``int` `arr[], ``int` `n)` `{` `    ``for` `(``int` `i = 0; i < n; i++) {` `        ``cout << arr[i] << ``" "``;` `        ``if` `((i + 1) % 3 == 0) {` `            ``cout << endl;` `        ``}` `    ``}` `}`   `int` `main()` `{` `    ``int` `arr[] = { -1, 2, -3, 4, 5, 6, -7, 8, 9 };` `    ``int` `n = ``sizeof``(arr) / ``sizeof``(arr[0]);` `    ``rearrange(arr, n);` `    ``cout << ``"Array after rearranging: "` `<< endl;` `    ``printArray(arr, n);` `    ``return` `0;` `}`   `// This code is contributed by sarojmcy2e`

## Java

 `public` `class` `Alternate {` `    ``static` `void` `rearrange(``int` `arr[], ``int` `n)` `    ``{` `        ``int` `i = -``1``, j = n;` `        ``while` `(``true``) {` `            ``// Move i to the next negative element` `            ``while` `(i < n - ``1` `&& arr[++i] >= ``0``) {` `            ``}`   `            ``// Move j to the next positive element` `            ``while` `(j > ``0` `&& arr[--j] < ``0``) {` `            ``}`   `            ``// If i and j cross, we have rearranged all` `            ``// elements` `            ``if` `(i >= j) {` `                ``return``;` `            ``}`   `            ``// Swap the positive and negative elements` `            ``int` `temp = arr[i];` `            ``arr[i] = arr[j];` `            ``arr[j] = temp;` `        ``}` `    ``}`   `    ``static` `void` `printArray(``int` `arr[], ``int` `n)` `    ``{` `        ``for` `(``int` `i = ``0``; i < n; i++) {` `            ``System.out.print(arr[i] + ``" "``);` `            ``if` `((i + ``1``) % ``3` `== ``0``) {` `                ``System.out.println();` `            ``}` `        ``}` `    ``}`   `    ``public` `static` `void` `main(String[] args)` `    ``{` `        ``int` `arr[] = { -``1``, ``2``, -``3``, ``4``, ``5``, ``6``, -``7``, ``8``, ``9` `};` `        ``int` `n = arr.length;` `        ``rearrange(arr, n);` `        ``System.out.println(``"Array after rearranging: "``);` `        ``printArray(arr, n);` `    ``}` `}`

## Python3

 `# Python implementation of above mentioned approach` `def` `rearrange(arr, n):` `    ``i ``=` `-``1` `    ``j ``=` `n` `    ``while` `True``:` `        ``# Move i to the next negative element` `        ``i ``+``=` `1` `        ``while` `i < n ``-` `1` `and` `arr[i] >``=` `0``:` `            ``i ``+``=` `1`   `        ``# Move j to the next positive element` `        ``j ``-``=` `1` `        ``while` `j > ``0` `and` `arr[j] < ``0``:` `            ``j ``-``=` `1`   `        ``# If i and j cross, we have rearranged all elements` `        ``if` `i >``=` `j:` `            ``return`   `        ``# Swap the positive and negative elements` `        ``temp ``=` `arr[i]` `        ``arr[i] ``=` `arr[j]` `        ``arr[j] ``=` `temp`     `def` `printArray(arr, n):` `    ``for` `i ``in` `range``(n):` `        ``print``(arr[i], end``=``" "``)` `        ``if` `(i ``+` `1``) ``%` `3` `=``=` `0``:` `            ``print``()`     `arr ``=` `[``-``1``, ``2``, ``-``3``, ``4``, ``5``, ``6``, ``-``7``, ``8``, ``9``]` `n ``=` `len``(arr)` `rearrange(arr, n)` `print``(``"Array after rearranging: "``)` `printArray(arr, n)`   `# This code is contributed by Tapesh(tapeshdua420)`

## C#

 `using` `System;`   `public` `class` `Program` `{` `    ``public` `static` `void` `Main()` `    ``{` `        ``int``[] arr = { -1, 2, -3, 4, 5, 6, -7, 8, 9 };` `        ``int` `n = arr.Length;`   `        ``Rearrange(arr, n);`   `        ``Console.WriteLine(``"Array after rearranging: "``);` `        ``PrintArray(arr, n);` `    ``}`   `    ``public` `static` `void` `Rearrange(``int``[] arr, ``int` `n)` `    ``{` `        ``int` `i = -1, j = n;` `        ``while` `(``true``)` `        ``{` `            ``// Move i to the next negative element` `            ``while` `(i < n - 1 && arr[++i] >= 0) {}`   `            ``// Move j to the next positive element` `            ``while` `(j > 0 && arr[--j] < 0) {}`   `            ``// If i and j cross, we have rearranged all elements` `            ``if` `(i >= j) {` `                ``return``;` `            ``}`   `            ``// Swap the positive and negative elements` `            ``int` `temp = arr[i];` `            ``arr[i] = arr[j];` `            ``arr[j] = temp;` `        ``}` `    ``}`   `    ``public` `static` `void` `PrintArray(``int``[] arr, ``int` `n)` `    ``{` `        ``for` `(``int` `i = 0; i < n; i++)` `        ``{` `            ``Console.Write(arr[i] + ``" "``);`   `            ``if` `((i + 1) % 3 == 0)` `            ``{` `                ``Console.WriteLine();` `            ``}` `        ``}` `    ``}` `}`

Output:-

```Array after rearranging:
9 2 8
4 5 6
-7 -3 -1 ```

Time Complexity:-he time complexity of the rearrange function is O(n), since it uses two while loops to iterate over the array once, swapping positive and negative elements as it goes.

Auxiliary Space:-The space complexity of both the rearrange and printArray functions is O(1), since they only use a fixed amount of extra space to store variables (i, j, temp, and n) and don’t create any additional data structures. Therefore, the overall space complexity of the program is also O(1).

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