Rearrange positive and negative numbers with constant extra space

Last Updated : 23 Jul, 2025

Given an array arr[] of integers, the task is to arrange them such that all negative integers appear before all the positive integers in the array without using any additional data structure like a hash table, arrays, etc. The order of appearance should be maintained.

Examples:  

Input: arr[] = [12, 11, -13, -5, 6, -7, 5, -3, -6]
Output: [-13, -5, -7, -3, -6, 12, 11, 6, 5]
Explanation: All negative elements [-13, -5, -7, -3, -6] were arranged before positive numbers [12, 11, 6, 5] and the relative ordering was also preserved.

Input: arr[] = [11, -13, 6, -7, 5]
Output: [-13, -7, 11, 6, 5]
Explanation: All negative elements [-13, -7] were arranged before positive numbers [11, 6, 5] and the relative ordering was also preserved.

Please remember:

  • Maintain the order : If we are not required to maintain the order. We can solve this problem with O(n) Time and (1) Space. Please refer Segregate Even and Odd for reference
  • O(1) Extra Space : If we are allowed to use an auxiliary array, we can solve this problem in O(n) Time and O(n) Extra Space. Please refer Move all negative elements to end for details.

The best time complexity that we could achieve here is O(n Log n).

Using Modified Insertion Sort

We can modify insertion sort to solve this problem.

Traverse the array from i = 1 to n - 1.

  • If the current element is positive, do nothing.
  • If the current element arr[i] is negative, we insert it into sequence arr[0 .. i-1] such that all positive elements in arr[0 .. i-1] are shifted one position to their right and arr[i] is inserted at index of first positive element.
C++
// C++ program to Rearrange positive and negative
// numbers in a array using
#include <iostream>
#include <vector>
using namespace std;

// Function to Rearrange positive and negative
// numbers in a array
void rearrange(vector<int>& arr) {
    for (int i = 1; i < arr.size(); i++) {

        // if current element is positive
        // do nothing
        if (arr[i] > 0)
            continue;

        // if current element is negative,
        // shift positive elements of arr[0..i-1],
        // to one position to their right 
      	int temp = arr[i];
        int j = i - 1;
        while (j >= 0 && arr[j] > 0) {
            arr[j + 1] = arr[j];
            j--;
        }

        // Put negative element at its right position
        arr[j + 1] = temp;
    }
}

int main() {
    vector<int> arr = {-12, 11, -13, -5, 6, -7, 5, -3, -6};
    
    rearrange(arr);
    for (int ele : arr) 
      	cout << ele << " ";
    return 0;
}
C
// C program to Rearrange positive and negative
// numbers in an array
#include <stdio.h>

void rearrange(int arr[], int size) {
    for (int i = 1; i < size; i++) {

        // if current element is positive
        // do nothing
        if (arr[i] > 0)
            continue;

        // if current element is negative,
        // shift positive elements of arr[0..i-1],
        // to one position to their right 
        int temp = arr[i];
        int j = i - 1;
        while (j >= 0 && arr[j] > 0) {
            arr[j + 1] = arr[j];
            j--;
        }

        // Put negative element at its right position
        arr[j + 1] = temp;
    }
}

int main() {
    int arr[] = {-12, 11, -13, -5, 6, -7, 5, -3, -6};
    int size = sizeof(arr) / sizeof(arr[0]);
    
    rearrange(arr, size);
    for (int i = 0; i < size; i++) 
        printf("%d ", arr[i]);
    return 0;
}
Java
// Java program to Rearrange positive and negative
// numbers in an array
import java.util.Arrays;

class GfG {
    static void rearrange(int[] arr) {
        for (int i = 1; i < arr.length; i++) {

            // if current element is positive
            // do nothing
            if (arr[i] > 0)
                continue;

            // if current element is negative,
            // shift positive elements of arr[0..i-1],
            // to one position to their right 
            int temp = arr[i];
            int j = i - 1;
            while (j >= 0 && arr[j] > 0) {
                arr[j + 1] = arr[j];
                j--;
            }

            // Put negative element at its right position
            arr[j + 1] = temp;
        }
    }

    public static void main(String[] args) {
        int[] arr = {-12, 11, -13, -5, 6, -7, 5, -3, -6};
        
        rearrange(arr);
      
      	for (int ele: arr)
        	System.out.print(ele + " ");
    }
}
Python
# Python program to Rearrange positive and negative
# numbers in an array

def rearrange(arr):
    for i in range(1, len(arr)):

        # if current element is positive
        # do nothing
        if arr[i] > 0:
            continue

        # if current element is negative,
        # shift positive elements of arr[0..i-1],
        # to one position to their right 
        temp = arr[i]
        j = i - 1
        while j >= 0 and arr[j] > 0:
            arr[j + 1] = arr[j]
            j -= 1

        # Put negative element at its right position
        arr[j + 1] = temp

if __name__ == "__main__":
    arr = [-12, 11, -13, -5, 6, -7, 5, -3, -6]
    rearrange(arr)
    for ele in arr:
    	print(ele, end = ' ')
C#
// C# program to Rearrange positive and negative
// numbers in an array
using System;

class GFG {
    static void rearrange(int[] arr) {
        for (int i = 1; i < arr.Length; i++) {

            // if current element is positive
            // do nothing
            if (arr[i] > 0)
                continue;

            // if current element is negative,
            // shift positive elements of arr[0..i-1],
            // to one position to their right 
            int temp = arr[i];
            int j = i - 1;
            while (j >= 0 && arr[j] > 0) {
                arr[j + 1] = arr[j];
                j--;
            }

            // Put negative element at its right position
            arr[j + 1] = temp;
        }
    }

    static void Main() {
        int[] arr = {-12, 11, -13, -5, 6, -7, 5, -3, -6};
        
        rearrange(arr);
        Console.WriteLine(string.Join(" ", arr));
    }
}
JavaScript
// JavaScript program to Rearrange positive and negative
// numbers in an array

function rearrange(arr) {
    for (let i = 1; i < arr.length; i++) {

        // if current element is positive
        // do nothing
        if (arr[i] > 0)
            continue;

        // if current element is negative,
        // shift positive elements of arr[0..i-1],
        // to one position to their right 
        let temp = arr[i];
        let j = i - 1;
        while (j >= 0 && arr[j] > 0) {
            arr[j + 1] = arr[j];
            j--;
        }

        // Put negative element at its right position
        arr[j + 1] = temp;
    }
}

// Driver Code
let arr = [-12, 11, -13, -5, 6, -7, 5, -3, -6];
rearrange(arr);
console.log(arr.join(" "));

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

Time Complexity: O(n2)
Auxiliary Space: O(1)

Sequentially Placing Negative element to the prefix

The idea is to move negative elements to the prefix of the array one by one. It means first we will find and place first negative element at index 0 and then second negative element at index 1 and so on. While placing negative numbers we will shift the block of positive numbers, as a whole.

Below is an illustration of how this will happen:

Current Array: [Ln, P1, P2, P3, N1, .......], Here, Ln is the prefix subarray(can be empty) that contains only negative elements. P1, P2, P3 is the block of positive numbers and N1 is the negative number that we want to move at correct place.

  • Swap P1 and N1, we get [Ln, N1, P2, P3, P1, ......]
  • Rotate this block of positive array by one position to right, i.e. rotate array [P2, P3, P1], we get [Ln, N1, P1, P2, P3, ......]

In this manner, the negative numbers will be placed on the left, maintaining their relative order, while the block of all positive numbers will be shifted to the right, also preserving their relative order.

C++
// C++ program to Rearrange positive and negative
// numbers in a array by sequentially Placing 
// Negative element to the prefix
#include <iostream>
#include <vector>
using namespace std;

void rotateSubArray(vector<int>& arr, int left, 
                    				int right) {
    int temp = arr[right];
    for (int i = right; i > left - 1; i--) {
      arr[i] = arr[i - 1];
    }
    arr[left] = temp;
}
 
void rearrange(vector<int>& arr) {
  
  	// pointer to last added negative number in prefix
    int idx = -1;
    
    for (int i = 0; i < arr.size(); i++) {
      if (arr[i] < 0) {
        idx++;
        
        // place current negative element after the 
        // last negative element added
        swap(arr[i], arr[idx]);
    
        // Rotate array to maintain order of positive numbers 
        // in the block arr[(idx + 1) ... i]
        if (i - idx >= 2)
          rotateSubArray(arr, idx + 1, i);
      }
    }
}

int main() {
    vector<int> arr = {5, 5, -3, 4, -8, 0, -7, 3, 
                       			-9, -3, 9, -2, 1};
    rearrange(arr);
  
    for (int ele: arr) {
      	cout << ele << " ";
    }
    return 0;
}
C
// C program to Rearrange positive and negative
// numbers in a array by sequentially Placing 
// Negative element to the prefix
#include <stdio.h>

void rotateSubArray(int arr[], int left, int right) {
    int temp = arr[right];
    for (int i = right; i > left - 1; i--) {
        arr[i] = arr[i - 1];
    }
    arr[left] = temp;
}

void rearrange(int arr[], int size) {
    // pointer to last added negative number in prefix
    int idx = -1;

    for (int i = 0; i < size; i++) {
        if (arr[i] < 0) {
            idx++;

            // place current negative element after the
            // last negative element added
            int temp = arr[i];
            arr[i] = arr[idx];
            arr[idx] = temp;

            // Rotate array to maintain order of positive numbers
            // in the block arr[(idx + 1) ... i]
            if (i - idx >= 2)
                rotateSubArray(arr, idx + 1, i);
        }
    }
}

int main() {
    int arr[] = {5, 5, -3, 4, -8, 0, -7, 3, -9,
                 		-3, 9, -2, 1};
    int size = sizeof(arr) / sizeof(arr[0]);

    rearrange(arr, size);

    for (int i = 0; i < size; i++) {
        printf("%d ", arr[i]);
    }
    return 0;
}
Java
// Java program to Rearrange positive and negative
// numbers in a array by sequentially Placing 
// Negative element to the prefix
import java.util.Arrays;

class GfG {

    static void rotateSubArray(int[] arr, int left, int right) {
        int temp = arr[right];
        for (int i = right; i > left - 1; i--) {
            arr[i] = arr[i - 1];
        }
        arr[left] = temp;
    }

    static void rearrange(int[] arr) {
      
        // pointer to last added negative number in prefix
        int idx = -1;

        for (int i = 0; i < arr.length; i++) {
            if (arr[i] < 0) {
                idx++;

                // place current negative element after the 
                // last negative element added
                int temp = arr[i];
                arr[i] = arr[idx];
                arr[idx] = temp;

                // Rotate array to maintain order of positive numbers 
                // in the block arr[(idx + 1) ... i]
                if (i - idx >= 2)
                    rotateSubArray(arr, idx + 1, i);
            }
        }
    }

    public static void main(String[] args) {
        int[] arr = {5, 5, -3, 4, -8, 0, -7, 3,
                     			-9, -3, 9, -2, 1};
        rearrange(arr);
      	for (int ele: arr)
        	System.out.print(ele + " ");
    }
}
Python
# Python program to Rearrange positive and negative
# numbers in a array by sequentially Placing 
# Negative element to the prefix

def rotateSubArray(arr, left, right):
    temp = arr[right]
    for i in range(right, left - 1, -1):
        arr[i] = arr[i - 1]
    arr[left] = temp

def rearrange(arr):
  
    # pointer to last added negative number in prefix
    idx = -1

    for i in range(len(arr)):
        if arr[i] < 0:
            idx += 1

            # place current negative element after the 
            # last negative element added
            arr[i], arr[idx] = arr[idx], arr[i]

            # Rotate array to maintain order of positive numbers 
            # in the block arr[(idx + 1) ... i]
            if i - idx >= 2:
                rotateSubArray(arr, idx + 1, i)

if __name__ == "__main__":
    arr = [5, 5, -3, 4, -8, 0, -7, 3, -9, -3, 9, -2, 1]
    rearrange(arr)
    for ele in arr:
    	print(ele, end = ' ')
C#
// C# program to Rearrange positive and negative
// numbers in a array by sequentially Placing 
// Negative element to the prefix
using System;

class GfG {

    static void rotateSubArray(int[] arr, int left, int right) {
        int temp = arr[right];
        for (int i = right; i > left - 1; i--) {
            arr[i] = arr[i - 1];
        }
        arr[left] = temp;
    }

    static void rearrange(int[] arr) {
      
        // pointer to last added negative number in prefix
        int idx = -1;

        for (int i = 0; i < arr.Length; i++) {
            if (arr[i] < 0) {
                idx++;

                // place current negative element after the 
                // last negative element added
                int temp = arr[i];
                arr[i] = arr[idx];
                arr[idx] = temp;

                // Rotate array to maintain order of positive numbers 
                // in the block arr[(idx + 1) ... i]
                if (i - idx >= 2)
                    rotateSubArray(arr, idx + 1, i);
            }
        }
    }

    static void Main() {
        int[] arr = {5, 5, -3, 4, -8, 0, -7, 3, -9,
                     			-3, 9, -2, 1};
        rearrange(arr);
      	for (int i = 0; i < arr.Length; i++)
        	Console.Write(arr[i] + " ");
    }
}
JavaScript
// JavaScript program to Rearrange positive and negative
// numbers in a array by sequentially Placing 
// Negative element to the prefix

function rotateSubArray(arr, left, right) {
    let temp = arr[right];
    for (let i = right; i > left - 1; i--) {
        arr[i] = arr[i - 1];
    }
    arr[left] = temp;
}

function rearrange(arr) {

    // pointer to last added negative number in prefix
    let idx = -1;

    for (let i = 0; i < arr.length; i++) {
        if (arr[i] < 0) {
            idx++;

            // place current negative element after the 
            // last negative element added
            [arr[i], arr[idx]] = [arr[idx], arr[i]];

            // Rotate array to maintain order of positive numbers 
            // in the block arr[(idx + 1) ... i]
            if (i - idx >= 2) {
                rotateSubArray(arr, idx + 1, i);
            }
        }
    }
}

// Driver Code
const arr = [5, 5, -3, 4, -8, 0, -7, 3, -9, 
								-3, 9, -2, 1];
rearrange(arr);
console.log(arr.join(" "));

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

Time Complexity: O(n2)
Auxiliary Space: O(1)

Using Modified Merge Sort (with extra space)

Merge method of standard merge sort algorithm can be modified to solve this problem. While merging two sorted halves say left and right, we need to merge in such a way that negative part of left and right sub-array is copied first followed by positive part of left and right sub-array.

C++
// C++ program to Rearrange positive and negative
// numbers in a array Using Optimized Merge Sort 
#include <iostream>
#include <vector>
using namespace std;

// Merges two subarrays of arr[].
// First subarray is arr[l..m]
// Second subarray is arr[m+1..r]
void merge(vector<int>& arr, int l, int m, int r) {
    int i, j, k;
    int n1 = m - l + 1;
    int n2 = r - m;

    // create temp arrays 
    vector<int> L(n1), R(n2);

    // Copy data to temp arrays L[] and R[] 
    for (i = 0; i < n1; i++)
        L[i] = arr[l + i];
    for (j = 0; j < n2; j++)
        R[j] = arr[m + 1 + j];

    // Merge the temp arrays back into arr[l..r]
    i = 0; 
    j = 0; 
    k = l; 

    // Note the order of appearance of elements should
    // be maintained - we copy elements of left subarray
    // first followed by that of right subarray

    // copy negative elements of left subarray
    while (i < n1 && L[i] < 0)
        arr[k++] = L[i++];

    // copy negative elements of right subarray
    while (j < n2 && R[j] < 0)
        arr[k++] = R[j++];

    // copy positive elements of left subarray
    while (i < n1)
        arr[k++] = L[i++];

    // copy positive elements of right subarray
    while (j < n2)
        arr[k++] = R[j++];
}

// Function to Rearrange positive and negative
// numbers in a array
void rearrange(vector<int>& arr, int l, int r) {
    if (l < r) {
        int m = l + (r - l) / 2;

        // Sort first and second halves
        rearrange(arr, l, m);
        rearrange(arr, m + 1, r);

        merge(arr, l, m, r);
    }
}

int main() {
    vector<int> arr = { -12, 11, -13, -5, 6, -7, 5, -3, -6 };
    rearrange(arr, 0, arr.size() - 1);

    for (int ele: arr) {
      	cout << ele << " ";
    }

    return 0;
}
C
// C program to Rearrange positive and negative
// numbers in an array Using Optimized Merge Sort
#include <stdio.h>
#include <stdlib.h>

// Merges two subarrays of arr[].
// First subarray is arr[l..m]
// Second subarray is arr[m+1..r]
void merge(int arr[], int l, int m, int r) {
    int i, j, k;
    int n1 = m - l + 1;
    int n2 = r - m;

    // create temp arrays 
    int* L = (int*)malloc(n1 * sizeof(int));
    int* R = (int*)malloc(n2 * sizeof(int));

    // Copy data to temp arrays L[] and R[] 
    for (i = 0; i < n1; i++)
        L[i] = arr[l + i];
    for (j = 0; j < n2; j++)
        R[j] = arr[m + 1 + j];

    // Merge the temp arrays back into arr[l..r]
    i = 0; 
    j = 0; 
    k = l;

    // copy negative elements of left subarray
    while (i < n1 && L[i] < 0)
        arr[k++] = L[i++];

    // copy negative elements of right subarray
    while (j < n2 && R[j] < 0)
        arr[k++] = R[j++];

    // copy positive elements of left subarray
    while (i < n1)
        arr[k++] = L[i++];

    // copy positive elements of right subarray
    while (j < n2)
        arr[k++] = R[j++];

    free(L);
    free(R);
}

// Function to Rearrange positive and negative
// numbers in an array
void rearrange(int arr[], int l, int r) {
    if (l < r) {
        int m = l + (r - l) / 2;

        // Sort first and second halves
        rearrange(arr, l, m);
        rearrange(arr, m + 1, r);

        merge(arr, l, m, r);
    }
}

int main() {
    int arr[] = { -12, 11, -13, -5, 6, -7, 5, -3, -6 };
    int n = sizeof(arr) / sizeof(arr[0]);
    rearrange(arr, 0, n - 1);

    for (int i = 0; i < n; i++)
        printf("%d ", arr[i]);

    return 0;
}
Java
// Java program to Rearrange positive and negative
// numbers in an array Using Optimized Merge Sort
import java.util.Arrays;

class GfG {

    // Merges two subarrays of arr[].
    // First subarray is arr[l..m]
    // Second subarray is arr[m+1..r]
    static void merge(int[] arr, int l, int m, int r) {
        int n1 = m - l + 1;
        int n2 = r - m;

        // create temp arrays 
        int[] L = new int[n1];
        int[] R = new int[n2];

        // Copy data to temp arrays L[] and R[] 
        System.arraycopy(arr, l, L, 0, n1);
        System.arraycopy(arr, m + 1, R, 0, n2);

        int i = 0, j = 0, k = l;

        // copy negative elements of left subarray
        while (i < n1 && L[i] < 0)
            arr[k++] = L[i++];

        // copy negative elements of right subarray
        while (j < n2 && R[j] < 0)
            arr[k++] = R[j++];

        // copy positive elements of left subarray
        while (i < n1)
            arr[k++] = L[i++];

        // copy positive elements of right subarray
        while (j < n2)
            arr[k++] = R[j++];
    }

    // Function to Rearrange positive and negative
    // numbers in an array
    static void rearrange(int[] arr, int l, int r) {
        if (l < r) {
            int m = l + (r - l) / 2;

            // Sort first and second halves
            rearrange(arr, l, m);
            rearrange(arr, m + 1, r);

            merge(arr, l, m, r);
        }
    }

    public static void main(String[] args) {
        int[] arr = { -12, 11, -13, -5, 6, -7, 5, -3, -6 };
        rearrange(arr, 0, arr.length - 1);
      	for (int ele: arr) 
        System.out.print(ele + " ");
    }
}
Python
# Python program to Rearrange positive and negative
# numbers in an array Using Optimized Merge Sort

# Merges two subarrays of arr[].
# First subarray is arr[l..m]
# Second subarray is arr[m+1..r]
def merge(arr, l, m, r):
    n1 = m - l + 1
    n2 = r - m

    # create temp arrays
    L = arr[l:m+1]
    R = arr[m+1:r+1]

    i = j = 0
    k = l

    # copy negative elements of left subarray
    while i < n1 and L[i] < 0:
        arr[k] = L[i]
        i += 1
        k += 1

    # copy negative elements of right subarray
    while j < n2 and R[j] < 0:
        arr[k] = R[j]
        j += 1
        k += 1

    # copy positive elements of left subarray
    while i < n1:
        arr[k] = L[i]
        i += 1
        k += 1

    # copy positive elements of right subarray
    while j < n2:
        arr[k] = R[j]
        j += 1
        k += 1

# Function to Rearrange positive and negative
# numbers in an array
def rearrange(arr, l, r):
    if l < r:
        m = l + (r - l) // 2

        # Sort first and second halves
        rearrange(arr, l, m)
        rearrange(arr, m + 1, r)

        merge(arr, l, m, r)

if __name__ == "__main__":
    arr = [-12, 11, -13, -5, 6, -7, 5, -3, -6]
    rearrange(arr, 0, len(arr) - 1)
    for ele in arr:
    	print(ele, end = ' ')
C#
// C# program to Rearrange positive and negative
// numbers in an array Using Optimized Merge Sort
using System;

class GFG {
  
    // Merges two subarrays of arr[].
    // First subarray is arr[l..m]
    // Second subarray is arr[m+1..r]
    static void merge(int[] arr, int l, int m, int r) {
        int n1 = m - l + 1;
        int n2 = r - m;

        // create temp arrays
        int[] L = new int[n1];
        int[] R = new int[n2];

        Array.Copy(arr, l, L, 0, n1);
        Array.Copy(arr, m + 1, R, 0, n2);

        int i = 0, j = 0, k = l;

        // copy negative elements of left subarray
        while (i < n1 && L[i] < 0)
            arr[k++] = L[i++];

        // copy negative elements of right subarray
        while (j < n2 && R[j] < 0)
            arr[k++] = R[j++];

        // copy positive elements of left subarray
        while (i < n1)
            arr[k++] = L[i++];

        // copy positive elements of right subarray
        while (j < n2)
            arr[k++] = R[j++];
    }

    // Function to Rearrange positive and negative
    // numbers in an array
    static void rearrange(int[] arr, int l, int r) {
        if (l < r) {
            int m = l + (r - l) / 2;

            // Sort first and second halves
            rearrange(arr, l, m);
            rearrange(arr, m + 1, r);

            merge(arr, l, m, r);
        }
    }

    static void Main() {
        int[] arr = { -12, 11, -13, -5, 6, -7, 5, -3, -6 };
        rearrange(arr, 0, arr.Length - 1);
		
      	for (int i = 0; i < arr.Length; i++)
        Console.Write(arr[i] + " ");
    }
}
JavaScript
// JavaScript program to Rearrange positive and negative
// numbers in an array Using Optimized Merge Sort

// Merges two subarrays of arr[].
// First subarray is arr[l..m]
// Second subarray is arr[m+1..r]
function merge(arr, l, m, r) {
    let n1 = m - l + 1;
    let n2 = r - m;

    // create temp arrays
    let L = arr.slice(l, m + 1);
    let R = arr.slice(m + 1, r + 1);

    let i = 0, j = 0, k = l;

    // copy negative elements of left subarray
    while (i < n1 && L[i] < 0)
        arr[k++] = L[i++];

    // copy negative elements of right subarray
    while (j < n2 && R[j] < 0)
        arr[k++] = R[j++];

    // copy positive elements of left subarray
    while (i < n1)
        arr[k++] = L[i++];

    // copy positive elements of right subarray
    while (j < n2)
        arr[k++] = R[j++];
}

// Function to Rearrange positive and negative
// numbers in an array
function rearrange(arr, l, r) {
    if (l < r) {
        let m = l + Math.floor((r - l) / 2);

        // Sort first and second halves
        rearrange(arr, l, m);
        rearrange(arr, m + 1, r);

        merge(arr, l, m, r);
    }
}

// Driver Code
let arr = [-12, 11, -13, -5, 6, -7, 5, -3, -6];
rearrange(arr, 0, arr.length - 1);
console.log(arr.join(" "));

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

Time complexity: O(n log n). 
Auxiliary Space: O(n + log n), log n, as implicit stack is used due to recursive call

Using Modified Merge Sort (without extra space)

The problem with the above approach is we are using an auxiliary array for merging but we're not allowed to use any data structure to solve this problem. We can do merging in place without using any data structure.

Let Ln and Lp denote the negative part and positive part of the left sub-array respectively. Similarly, Rn and Rp denote the negative and positive parts of the right sub-array respectively. 

Below are the steps to convert [Ln Lp Rn Rp] to [Ln Rn Lp Rp] without using extra space, where [Ln Rn] is the negative subarray and [Ln Rn]. 

  1. Reverse Lp and Rn. We get [Lp] -> [Lp'] and [Rn] -> [Rn'] [Ln Lp Rn Rp] -> [Ln Lp’ Rn’ Rp]
  2. Reverse [Lp’ Rn’]. We get [Rn Lp]. [Ln Lp’ Rn’ Rp] -> [Ln Rn Lp Rp]
C++
// C++ program to Rearrange positive and negative
// numbers in a array
#include <iostream>
#include <vector>
using namespace std;

// Function to reverse the subarray arr[l...r]
void reverse(vector<int>& arr, int l, int r) {
    if (l < r) {
        swap(arr[l], arr[r]);
        reverse(arr, ++l, --r);
    }
}

// Merges two subarrays of arr[].
// First subarray is arr[l..m]
// Second subarray is arr[m+1..r]
void merge(vector<int>& arr, int l, int m, int r) {
    int i = l;
    int j = m + 1;

  	// find starting index of positive part in the 
  	// first half i.e., find starting index of Lp
    while (i <= m && arr[i] < 0)
        i++;

    // find ending index of negative part in the 
  	// first second i.e., find ending index of Rn
    while (j <= r && arr[j] < 0)
        j++;
	j--;

    // reverse positive part of
    // left sub-array (arr[i..m])
    reverse(arr, i, m);

    // reverse negative part of
    // right sub-array (arr[m+1..j])
    reverse(arr, m + 1, j);

    // reverse arr[i..j]
    reverse(arr, i, j);
}

// Function to Rearrange positive and negative
// numbers in a array
void rearrange(vector<int>& arr, int l, int r) {
    if (l < r) {
        int m = l + (r - l) / 2;

        // Sort first and second halves
        rearrange(arr, l, m);
        rearrange(arr, m + 1, r);

        merge(arr, l, m, r);
    }
}

int main() {
    vector<int> arr = { -12, 11, -13, -5, 6, -7, 5, -3, -6 };
    rearrange(arr, 0, arr.size() - 1);

    for (int ele: arr) {
      	cout << ele << " ";
    }

    return 0;
}
C
// C program to Rearrange positive and negative
// numbers in an array
#include <stdio.h>

void swap(int* a, int* b) {
    int temp = *a;
    *a = *b;
    *b = temp;
}

// Function to reverse the subarray arr[l...r]
void reverse(int arr[], int l, int r) {
    if (l < r) {
        swap(&arr[l], &arr[r]);
        reverse(arr, ++l, --r);
    }
}

// Merges two subarrays of arr[].
// First subarray is arr[l..m]
// Second subarray is arr[m+1..r]
void merge(int arr[], int l, int m, int r) {
    int i = l;
    int j = m + 1;

    // find starting index of positive part in the 
    // first half i.e., find starting index of Lp
    while (i <= m && arr[i] < 0)
        i++;

    // find ending index of negative part in the 
    // first second i.e., find ending index of Rn
    while (j <= r && arr[j] < 0)
        j++;
    j--;

    // reverse positive part of
    // left sub-array (arr[i..m])
    reverse(arr, i, m);

    // reverse negative part of
    // right sub-array (arr[m+1..j])
    reverse(arr, m + 1, j);

    // reverse arr[i..j]
    reverse(arr, i, j);
}

// Function to Rearrange positive and negative
// numbers in an array
void rearrange(int arr[], int l, int r) {
    if (l < r) {
        int m = l + (r - l) / 2;

        // Sort first and second halves
        rearrange(arr, l, m);
        rearrange(arr, m + 1, r);

        merge(arr, l, m, r);
    }
}

int main() {
    int arr[] = { -12, 11, -13, -5, 6, -7, 5, -3, -6 };
    int size = sizeof(arr) / sizeof(arr[0]);

    rearrange(arr, 0, size - 1);

    for (int i = 0; i < size; i++)
        printf("%d ", arr[i]);

    return 0;
}
Java
// Java program to Rearrange positive and negative
// numbers in an array
import java.util.Arrays;

class GfG {

    // Function to reverse the subarray arr[l...r]
    static void reverse(int[] arr, int l, int r) {
        if (l < r) {
            int temp = arr[l];
            arr[l] = arr[r];
            arr[r] = temp;
            reverse(arr, ++l, --r);
        }
    }

    // Merges two subarrays of arr[].
    // First subarray is arr[l..m]
    // Second subarray is arr[m+1..r]
    static void merge(int[] arr, int l, int m, int r) {
        int i = l;
        int j = m + 1;

        // find starting index of positive part in the 
        // first half i.e., find starting index of Lp
        while (i <= m && arr[i] < 0)
            i++;

        // find ending index of negative part in the 
        // first second i.e., find ending index of Rn
        while (j <= r && arr[j] < 0)
            j++;
        j--;

        // reverse positive part of
        // left sub-array (arr[i..m])
        reverse(arr, i, m);

        // reverse negative part of
        // right sub-array (arr[m+1..j])
        reverse(arr, m + 1, j);

        // reverse arr[i..j]
        reverse(arr, i, j);
    }

    // Function to Rearrange positive and negative
    // numbers in an array
    static void rearrange(int[] arr, int l, int r) {
        if (l < r) {
            int m = l + (r - l) / 2;

            // Sort first and second halves
            rearrange(arr, l, m);
            rearrange(arr, m + 1, r);

            merge(arr, l, m, r);
        }
    }

    public static void main(String[] args) {
        int[] arr = { -12, 11, -13, -5, 6, -7, 5, -3, -6 };
        rearrange(arr, 0, arr.length - 1);

      	for (int ele: arr)
        System.out.print(ele + " ");
    }
}
Python
# Python program to Rearrange positive and negative
# numbers in an array

# Function to reverse the subarray arr[l...r]
def reverse(arr, l, r):
    if l < r:
        arr[l], arr[r] = arr[r], arr[l]
        reverse(arr, l + 1, r - 1)

# Merges two subarrays of arr[].
# First subarray is arr[l..m]
# Second subarray is arr[m+1..r]
def merge(arr, l, m, r):
    i = l
    j = m + 1

    # find starting index of positive part in the 
    # first half i.e., find starting index of Lp
    while i <= m and arr[i] < 0:
        i += 1

    # find ending index of negative part in the 
    # first second i.e., find ending index of Rn
    while j <= r and arr[j] < 0:
        j += 1
    j -= 1

    # reverse positive part of left sub-array (arr[i..m])
    reverse(arr, i, m)

    # reverse negative part of right sub-array (arr[m+1..j])
    reverse(arr, m + 1, j)

    # reverse arr[i..j]
    reverse(arr, i, j)

# Function to Rearrange positive and negative
# numbers in an array
def rearrange(arr, l, r):
    if l < r:
        m = l + (r - l) // 2

        # Sort first and second halves
        rearrange(arr, l, m)
        rearrange(arr, m + 1, r)

        merge(arr, l, m, r)

if __name__ == "__main__":
    arr = [-12, 11, -13, -5, 6, -7, 5, -3, -6]
    rearrange(arr, 0, len(arr) - 1)
    for ele in arr:
    	print(ele, end = ' ')
C#
// C# program to Rearrange positive and negative
// numbers in an array
using System;

class GFG {

    // Function to reverse the subarray arr[l...r]
    static void Reverse(int[] arr, int l, int r) {
        if (l < r) {
            int temp = arr[l];
            arr[l] = arr[r];
            arr[r] = temp;
            Reverse(arr, ++l, --r);
        }
    }

    // Merges two subarrays of arr[].
    // First subarray is arr[l..m]
    // Second subarray is arr[m+1..r]
    static void Merge(int[] arr, int l, int m, int r) {
        int i = l;
        int j = m + 1;

        // find starting index of positive part in the 
        // first half i.e., find starting index of Lp
        while (i <= m && arr[i] < 0)
            i++;

        // find ending index of negative part in the 
        // first second i.e., find ending index of Rn
        while (j <= r && arr[j] < 0)
            j++;
        j--;

        // reverse positive part of left sub-array (arr[i..m])
        Reverse(arr, i, m);

        // reverse negative part of right sub-array (arr[m+1..j])
        Reverse(arr, m + 1, j);

        // reverse arr[i..j]
        Reverse(arr, i, j);
    }

    // Function to Rearrange positive and negative
    // numbers in an array
    static void Rearrange(int[] arr, int l, int r) {
        if (l < r) {
            int m = l + (r - l) / 2;

            // Sort first and second halves
            Rearrange(arr, l, m);
            Rearrange(arr, m + 1, r);

            Merge(arr, l, m, r);
        }
    }

    static void Main() {
        int[] arr = { -12, 11, -13, -5, 6, -7, 5, -3, -6 };
        Rearrange(arr, 0, arr.Length - 1);
		
      	for (int i = 0; i < arr.Length; i++)
        Console.Write(arr[i] + " ");
    }
}
JavaScript
// JavaScript program to Rearrange positive and negative
// numbers in an array

// Function to reverse the subarray arr[l...r]
function reverse(arr, l, r) {
    if (l < r) {
        [arr[l], arr[r]] = [arr[r], arr[l]];
        reverse(arr, ++l, --r);
    }
}

// Merges two subarrays of arr[].
// First subarray is arr[l..m]
// Second subarray is arr[m+1..r]
function merge(arr, l, m, r) {
    let i = l;
    let j = m + 1;

    // find starting index of positive part in the 
    // first half i.e., find starting index of Lp
    while (i <= m && arr[i] < 0)
        i++;

    // find ending index of negative part in the 
    // first second i.e., find ending index of Rn
    while (j <= r && arr[j] < 0)
        j++;
    j--;

    // reverse positive part of left sub-array (arr[i..m])
    reverse(arr, i, m);

    // reverse negative part of right sub-array (arr[m+1..j])
    reverse(arr, m + 1, j);

    // reverse arr[i..j]
    reverse(arr, i, j);
}

// Function to Rearrange positive and negative
// numbers in an array
function rearrange(arr, l, r) {
    if (l < r) {
        let m = l + Math.floor((r - l) / 2);

        // Sort first and second halves
        rearrange(arr, l, m);
        rearrange(arr, m + 1, r);

        merge(arr, l, m, r);
    }
}

// Driver Code
let arr = [-12, 11, -13, -5, 6, -7, 5, -3, -6];
rearrange(arr, 0, arr.length - 1);
console.log(arr.join(' '));

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

Time complexity: O(n log n),
Auxiliary Space: O(log n), as implicit stack is used due to recursive call

Comment