Skip to content

# Move all negative numbers to beginning and positive to end with constant extra space

• Difficulty Level : Easy
• Last Updated : 14 Jun, 2022

An array contains both positive and negative numbers in random order. Rearrange the array elements so that all negative numbers appear before all positive numbers.

Examples :

Input: -12, 11, -13, -5, 6, -7, 5, -3, -6
Output: -12 -13 -5 -7 -3 -6 11 6 5

Note: Order of elements is not important here.

Naive approach: The idea is to sort the array of elements, this will make sure that all the negative elements will come before all the positive elements.
Below is the implementation of the above approach:

## C++

 `#include ` `#include` `#include` `using` `namespace` `std;` `void` `move(vector<``int``>& arr){` `  ``sort(arr.begin(),arr.end());` `}` `int` `main() {`   `    ``vector<``int``> arr = { -1, 2, -3, 4, 5, 6, -7, 8, 9 };` `      ``move(arr);` `    ``for` `(``int` `e : arr)` `       ``cout<

## Java

 `// Java program to move all negative numbers to the` `// beginning and all positive numbers to the end with` `// constant extra space` `import` `java.util.*;` `public` `class` `Gfg {` `   `  `    ``public` `static` `void` `move(``int``[] arr)` `    ``{` `        ``Arrays.sort(arr);` `    ``}`   `    ``// Driver code` `    ``public` `static` `void` `main(String[] args)` `    ``{` `        ``int``[] arr = { -``1``, ``2``, -``3``, ``4``, ``5``, ``6``, -``7``, ``8``, ``9` `};` `        ``move(arr);` `        ``for` `(``int` `e : arr)` `            ``System.out.print(e + ``" "``);` `    ``}` `}` `// This article is contributed by aadityapburujwale`

## Python3

 `# Python code for the same approach` `def` `move(arr):` `  ``arr.sort()`   `# driver code` `arr ``=` `[ ``-``1``, ``2``, ``-``3``, ``4``, ``5``, ``6``, ``-``7``, ``8``, ``9` `]` `move(arr)` `for` `e ``in` `arr:` `    ``print``(e , end ``=` `" "``)`   `# This code is contributed by shinjanpatra`

## C#

 `// C# program to move all negative numbers to the` `// beginning and all positive numbers to the end with` `// constant extra space` `using` `System;` `using` `System.Collections;` `public` `class` `Gfg {` `   `  `    ``public` `static` `void` `move(``int``[] arr)` `    ``{` `        ``Array.Sort(arr);` `    ``}`   `    ``// Driver code` `    ``public` `static` `void` `Main()` `    ``{` `        ``int``[] arr = { -1, 2, -3, 4, 5, 6, -7, 8, 9 };` `        ``move(arr);` `        ``foreach` `(``int` `e ``in` `arr)` `            ``Console.Write(e + ``" "``);` `    ``}` `}` `// This code is contributed by Saurabh Jaiswal`

## Javascript

 ``

Output

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

Time Complexity: O(n*log(n)), Where n is the length of the given array.
Auxiliary Space: O(n)

Efficient Approach 1:
The idea is to simply apply the partition process of quicksort

## C++

 `// A C++ program to put all negative` `// numbers before positive numbers` `#include ` `using` `namespace` `std;`   `void` `rearrange(``int` `arr[], ``int` `n)` `{` `    ``int` `j = 0;` `    ``for` `(``int` `i = 0; i < n; i++) {` `        ``if` `(arr[i] < 0) {` `            ``if` `(i != j)` `                ``swap(arr[i], arr[j]);` `            ``j++;` `        ``}` `    ``}` `}`   `// A utility function to print an array` `void` `printArray(``int` `arr[], ``int` `n)` `{` `    ``for` `(``int` `i = 0; i < n; i++)` `        ``printf``(``"%d "``, arr[i]);` `}`   `// Driver code` `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

 `// Java program to put all negative` `// numbers before positive numbers` `import` `java.io.*;`   `class` `GFG {`   `    ``static` `void` `rearrange(``int` `arr[], ``int` `n)` `    ``{` `        ``int` `j = ``0``, temp;` `        ``for` `(``int` `i = ``0``; i < n; i++) {` `            ``if` `(arr[i] < ``0``) {` `                ``if` `(i != j) {` `                    ``temp = arr[i];` `                    ``arr[i] = arr[j];` `                    ``arr[j] = temp;` `                ``}` `                ``j++;` `            ``}` `        ``}` `    ``}`   `    ``// 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 code` `    ``public` `static` `void` `main(String args[])` `    ``{` `        ``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 Nikita Tiwari.`

## Python3

 `# A Python 3 program to put` `# all negative numbers before` `# positive numbers`   `def` `rearrange(arr, n ) :`   `    ``# Please refer partition() in ` `    ``# below post` `    ``# https://www.geeksforgeeks.org / quick-sort / j = 0` `    ``j ``=` `0` `    ``for` `i ``in` `range``(``0``, n) :` `        ``if` `(arr[i] < ``0``) :` `            ``temp ``=` `arr[i]` `            ``arr[i] ``=` `arr[j]` `            ``arr[j]``=` `temp` `            ``j ``=` `j ``+` `1` `    ``print``(arr)`   `# Driver code` `arr ``=` `[``-``1``, ``2``, ``-``3``, ``4``, ``5``, ``6``, ``-``7``, ``8``, ``9``]` `n ``=` `len``(arr)` `rearrange(arr, n)`     `# This code is contributed by Nikita Tiwari.`

## C#

 `// C# program to put all negative` `// numbers before positive numbers` `using` `System;`   `class` `GFG {` `    ``static` `void` `rearrange(``int``[] arr, ``int` `n)` `    ``{`   `        ``int` `j = 0, temp;` `        ``for` `(``int` `i = 0; i < n; i++) {` `            ``if` `(arr[i] < 0) {` `                ``temp = arr[i];` `                ``arr[i] = arr[j];` `                ``arr[j] = temp;` `                ``j++;` `            ``}` `        ``}` `    ``}`   `    ``// 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 code` `    ``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 nitin mittal.`

## PHP

 ``

## Javascript

 ``

Output

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

Time complexity: O(N)
Auxiliary Space: O(1)

Two Pointer Approach: The idea is to solve this problem with constant space and linear time is by using a two-pointer or two-variable approach where we simply take two variables like left and right which hold the 0 and N-1 indexes. Just need to check that :

1. Check If the left and right pointer elements are negative then simply increment the left pointer.
2. Otherwise, if the left element is positive and the right element is negative then simply swap the elements, and simultaneously increment and decrement the left and right pointers.
3. Else if the left element is positive and the right element is also positive then simply decrement the right pointer.
4. Repeat the above 3 steps until the left pointer â‰¤ right pointer.

Below is the implementation of the above approach:

## C++

 `// C++ program of the above ` `// approach`   `#include ` `using` `namespace` `std;`   `// Function to shift all the` `// negative elements on left side` `void` `shiftall(``int` `arr[], ``int` `left, ` `              ``int` `right)` `{` `  `  `  ``// Loop to iterate over the ` `  ``// array from left to the right` `  ``while` `(left<=right)` `  ``{` `    ``// Condition to check if the left` `    ``// and the right elements are ` `    ``// negative` `    ``if` `(arr[left] < 0 && arr[right] < 0)` `      ``left+=1;` `    `  `    ``// Condition to check if the left ` `    ``// pointer element is positive and ` `    ``// the right pointer element is negative` `    ``else` `if` `(arr[left]>0 && arr[right]<0)` `    ``{` `      ``int` `temp=arr[left];` `      ``arr[left]=arr[right];` `      ``arr[right]=temp;` `      ``left+=1;` `      ``right-=1;` `    ``}` `    `  `    ``// Condition to check if both the ` `    ``// elements are positive` `    ``else` `if` `(arr[left]>0 && arr[right] >0)` `      ``right-=1;` `    ``else``{` `      ``left += 1;` `      ``right -= 1;` `    ``}` `  ``}` `}`   `// Function to print the array` `void` `display(``int` `arr[], ``int` `right){` `  `  `  ``// Loop to iterate over the element` `  ``// of the given array` `  ``for` `(``int` `i=0;i<=right;++i){` `    ``cout<

## Java

 `// Java program of the above` `// approach` `import` `java.io.*;`   `class` `GFG{`   `// Function to shift all the` `// negative elements on left side` `static` `void` `shiftall(``int``[] arr, ``int` `left,` `                     ``int` `right)` `{` `    `  `    ``// Loop to iterate over the` `    ``// array from left to the right` `    ``while` `(left <= right) ` `    ``{` `        `  `        ``// Condition to check if the left` `        ``// and the right elements are` `        ``// negative` `        ``if` `(arr[left] < ``0` `&& arr[right] < ``0``)` `            ``left++;`   `        ``// Condition to check if the left` `        ``// pointer element is positive and` `        ``// the right pointer element is negative` `        ``else` `if` `(arr[left] > ``0` `&& arr[right] < ``0``)` `        ``{` `            ``int` `temp = arr[left];` `            ``arr[left] = arr[right];` `            ``arr[right] = temp;` `            ``left++;` `            ``right--;` `        ``}`   `        ``// Condition to check if both the` `        ``// elements are positive` `        ``else` `if` `(arr[left] > ``0` `&& arr[right] > ``0``)` `            ``right--;` `        ``else` `        ``{` `            ``left++;` `            ``right--;` `        ``}` `    ``}` `}`   `// Function to print the array` `static` `void` `display(``int``[] arr, ``int` `right)` `{` `    `  `    ``// Loop to iterate over the element` `    ``// of the given array` `    ``for``(``int` `i = ``0``; i <= right; ++i)` `        ``System.out.print(arr[i] + ``" "``);` `        `  `    ``System.out.println();` `}`   `// Drive code` `public` `static` `void` `main(String[] args)` `{` `    ``int``[] arr = { -``12``, ``11``, -``13``, -``5``, ` `                   ``6``, -``7``, ``5``, -``3``, ``11` `};` `                   `  `    ``int` `arr_size = arr.length;`   `    ``// Function Call` `    ``shiftall(arr, ``0``, arr_size - ``1``);` `    ``display(arr, arr_size - ``1``);` `}` `}`   `// This code is contributed by dhruvgoyal267`

## Python3

 `# Python3 program of the ` `# above approach`   `# Function to shift all the ` `# the negative elements to` `# the left of the array` `def` `shiftall(arr,left,right):` `  `  `  ``# Loop to iterate while the ` `  ``# left pointer is less than` `  ``# the right pointer` `  ``while` `left<``=``right:` `    `  `    ``# Condition to check if the left` `    ``# and right pointer negative` `    ``if` `arr[left] < ``0` `and` `arr[right] < ``0``:` `      ``left``+``=``1` `      `  `    ``# Condition to check if the left ` `    ``# pointer element is positive and ` `    ``# the right pointer element is` `    ``# negative` `    ``else` `if` `arr[left]>``0` `and` `arr[right]<``0``:` `      ``arr[left], arr[right] ``=` `\` `              ``arr[right],arr[left]` `      ``left``+``=``1` `      ``right``-``=``1` `      `  `    ``# Condition to check if the left` `    ``# pointer is positive and right ` `    ``# pointer as well` `    ``else` `if` `arr[left]>``0` `and` `arr[right]>``0``:` `      ``right``-``=``1` `    ``else``:` `      ``left``+``=``1` `      ``right``-``=``1` `      `  `# Function to print the array` `def` `display(arr):` `  ``for` `i ``in` `range``(``len``(arr)):` `    ``print``(arr[i], end``=``" "``)` `  ``print``()`   `# Driver Code` `if` `__name__ ``=``=` `"__main__"``:` `  ``arr``=``[``-``12``, ``11``, ``-``13``, ``-``5``, \` `       ``6``, ``-``7``, ``5``, ``-``3``, ``11``]` `  ``n``=``len``(arr)` `  ``shiftall(arr,``0``,n``-``1``)` `  ``display(arr)`   `# Sumit Singh`

## C#

 `// C# program of the above` `// approach` `using` `System.IO;` `using` `System;` `class` `GFG` `{` `    ``// Function to shift all the` `    ``// negative elements on left side` `    ``static` `void` `shiftall(``int``[] arr, ``int` `left,``int` `right)` `    ``{` `      `  `        ``// Loop to iterate over the` `        ``// array from left to the right` `        ``while` `(left <= right) ` `        ``{` `         `  `            ``// Condition to check if the left` `            ``// and the right elements are` `            ``// negative` `            ``if` `(arr[left] < 0 && arr[right] < 0)` `                ``left++;` ` `  `            ``// Condition to check if the left` `            ``// pointer element is positive and` `            ``// the right pointer element is negative` `            ``else` `if` `(arr[left] > 0 && arr[right] < 0)` `            ``{` `                ``int` `temp = arr[left];` `                ``arr[left] = arr[right];` `                ``arr[right] = temp;` `                ``left++;` `                ``right--;` `            ``}` ` `  `            ``// Condition to check if both the` `            ``// elements are positive` `            ``else` `if` `(arr[left] > 0 && arr[right] > 0)` `                ``right--;` `            ``else` `            ``{` `                ``left++;` `                ``right--;` `            ``}` `        ``}` `    ``}` `  `  `    ``// Function to print the array` `    ``static` `void` `display(``int``[] arr, ``int` `right)` `    ``{` `      `  `        ``// Loop to iterate over the element` `        ``// of the given array` `        ``for``(``int` `i = 0; i <= right; ++i)` `        ``{` `            ``Console.Write(arr[i] + ``" "``);` `            `  `        ``}` `        ``Console.WriteLine();` `    ``}` `    `  `    ``// Drive code                   ` `    ``static` `void` `Main()` `    ``{` `        ``int``[] arr = {-12, 11, -13, -5, 6, -7, 5, -3, 11};` `        ``int` `arr_size = arr.Length;` `        ``shiftall(arr, 0, arr_size - 1);` `        ``display(arr, arr_size - 1);` `    ``}` `}`   `// This code is contributed by avanitrachhadiya2155`

## Javascript

 ``

Output

`-12 -3 -13 -5 -7 6 5 11 11 `

This is an in-place rearranging algorithm for arranging the positive and negative numbers where the order of elements is not maintained.
Time Complexity: O(N)
Auxiliary Space: O(1)

The problem becomes difficult if we need to maintain the order of elements. Please refer to Rearrange positive and negative numbers with constant extra space for details.

This article is contributed by Apoorva. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeek’s main page and help other Geeks.

Approach 3:
Here, we will use the famous Dutch National Flag Algorithm for two “colors”. The first color will be for all negative integers and the second color will be for all positive integers. We will divide the array into three partitions with the help of two pointers, low and high.

1. ar[1…low-1] negative integers
2. ar[low…high] unknown
3. ar[high+1…N] positive integers

Now, we explore the array with the help of low pointer, shrinking the unknown partition, and moving elements to their correct partition in the process. We do this until we have explored all the elements, and size of the unknown partition shrinks to zero.

Below is the implementation of the above approach:

## C++

 `#include ` `using` `namespace` `std;`   `// Swap Function.` `void` `swap(``int` `&a,``int` `&b){` `  ``int` `temp =a;` `  ``a=b;` `  ``b=temp;` `}` `  `  `// Using Dutch National Flag Algorithm.` `void` `reArrange(``int` `arr[],``int` `n){` `      ``int` `low =0,high = n-1;` `      ``while``(low0){` `          ``high--;` `      ``}``else``{` `        ``swap(arr[low],arr[high]);` `      ``}` `    ``}` `}` `void` `displayArray(``int` `arr[],``int` `n){` `  ``for``(``int` `i=0;i

## Java

 `// Java program to move all negative numbers to the` `// beginning and all positive numbers to the end with` `// constant extra space`   `public` `class` `Gfg {`   `    ``// a utility function to swap two elements of an array` `    ``public` `static` `void` `swap(``int``[] ar, ``int` `i, ``int` `j)` `    ``{` `        ``int` `t = ar[i];` `        ``ar[i] = ar[j];` `        ``ar[j] = t;` `    ``}`   `    ``// function to shilf all negative integers to the left` `    ``// and all positive integers to the right` `    ``// using Dutch National Flag Algorithm` `    ``public` `static` `void` `move(``int``[] ar)` `    ``{` `        ``int` `low = ``0``;` `        ``int` `high = ar.length - ``1``;` `        ``while` `(low <= high) {` `            ``if` `(ar[low] <= ``0``)` `                ``low++;` `            ``else` `                ``swap(ar, low, high--);` `        ``}` `    ``}`   `    ``// Driver code` `    ``public` `static` `void` `main(String[] args)` `    ``{` `        ``int``[] ar = { ``1``, ``2``,  -``4``, -``5``, ``2``, -``7``, ``3``,` `                     ``2``, -``6``, -``8``, -``9``, ``3``, ``2``,  ``1` `};` `        ``move(ar);` `        ``for` `(``int` `e : ar)` `            ``System.out.print(e + ``" "``);` `    ``}` `}`   `// This code is contributed by Vedant Harshit`

## Python3

 `# Python code for the approach`   `# Using Dutch National Flag Algorithm.` `def` `reArrange(arr, n):` `    ``low,high ``=` `0``, n ``-` `1` `    ``while``(low ``0``):` `            ``high ``-``=` `1` `        ``else``:` `            ``arr[low],arr[high] ``=` `arr[high],arr[low]`   `def` `displayArray(arr, n):`   `    ``for` `i ``in` `range``(n):` `        ``print``(arr[i],end ``=` `" "``)` `  `  `    ``print``('')`   `# driver code` `# Data` `arr ``=` `[``1``, ``2``,  ``-``4``, ``-``5``, ``2``, ``-``7``, ``3``, ``2``, ``-``6``, ``-``8``, ``-``9``, ``3``, ``2``,  ``1``]` `n ``=` `len``(arr)` `reArrange(arr,n)` `displayArray(arr,n)`   `# This code is contributed by shinjanpatra`

## C#

 `// Include namespace system` `using` `System;`   `// C# program to move all negative numbers to the` `// beginning and all positive numbers to the end with` `// constant extra space` `public` `class` `Gfg` `{` `  ``// a utility function to swap two elements of an array` `  ``public` `static` `void` `swap(``int``[] ar, ``int` `i, ``int` `j)` `  ``{` `    ``var` `t = ar[i];` `    ``ar[i] = ar[j];` `    ``ar[j] = t;` `  ``}` `  ``// function to shilf all negative integers to the left` `  ``// and all positive integers to the right` `  ``// using Dutch National Flag Algorithm` `  ``public` `static` `void` `move(``int``[] ar)` `  ``{` `    ``var` `low = 0;` `    ``var` `high = ar.Length - 1;` `    ``while` `(low <= high)` `    ``{` `      ``if` `(ar[low] <= 0)` `      ``{` `        ``low++;` `      ``}` `      ``else` `      ``{` `        ``Gfg.swap(ar, low, high--);` `      ``}` `    ``}` `  ``}`   `  ``// Driver code` `  ``public` `static` `void` `Main(String[] args)` `  ``{` `    ``int``[] ar = {1, 2, -4, -5, 2, -7, 3, 2, -6, -8, -9, 3, 2, 1};` `    ``Gfg.move(ar);` `    ``foreach` `(``int` `e ``in` `ar)` `    ``{            Console.Write(e.ToString() + ``" "``);` `    ``}` `  ``}` `}`   `// This code is contributed by mukulsomukesh`

## Javascript

 ``

Output

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

Time complexity: O(N)
Auxiliary Space: O(1)

The order of elements does not matter here. Explanation and code contributed by Vedant Harshit

My Personal Notes arrow_drop_up
Recommended Articles
Page :