Positive elements at even and negative at odd positions (Relative order not maintained)

09 Jun, 2022
You have been given an array and you have to make a program to convert that array such that positive elements occur at even numbered places in the array and negative elements occur at odd numbered places in the array. We have to do it in place.There can be unequal number of positive and negative values and the extra values have to left as it is.
Examples:  
Input : arr[] = {1, -3, 5, 6, -3, 6, 7, -4, 9, 10}
Output : arr[] = {1, -3, 5, -3, 6, 6, 7, -4, 9, 10}

Input : arr[] = {-1, 3, -5, 6, 3, 6, -7, -4, -9, 10}
Output : arr[] = {3, -1, 6, -5, 3, -7, 6, -4, 10, -9}
The idea is to use Hoare’s partition process of Quick Sort. We take two pointers positive and negative. We set the positive pointer at start of the array and the negative pointer at 1st position of the array. 
We move positive pointer two steps forward till it finds a negative element. Similarly, we move negative pointer forward by two places till it finds a positive value at its position. 
If the positive and negative pointers are in the array then we will swap the values at these indexes otherwise we will stop executing the process.
C++
Java
Python3
C#
PHP
Javascript
// C++ program to rearrange positive and negative// numbers#include <bits/stdc++.h>using namespace std; void rearrange(int a[], int size){    int positive = 0, negative = 1;     while (true) {         /* Move forward the positive pointer till         negative number number not encountered */        while (positive < size && a[positive] >= 0)            positive += 2;         /* Move forward the negative pointer till         positive number number not encountered   */        while (negative < size && a[negative] <= 0)            negative += 2;         // Swap array elements to fix their position.        if (positive < size && negative < size)            swap(a[positive], a[negative]);         /* Break from the while loop when any index            exceeds the size of the array */        else            break;    }} // Driver codeint main(){    int arr[] = { 1, -3, 5, 6, -3, 6, 7, -4, 9, 10 };    int n = (sizeof(arr) / sizeof(arr[0]));     rearrange(arr, n);    for (int i = 0; i < n; i++)        cout << arr[i] << " ";     return 0;}
// Java program to rearrange positive// and negative numbersimport java.io.*; class GFG { static void rearrange(int a[], int size){  int positive = 0, negative = 1, temp;     while (true) {     /* Move forward the positive pointer till    negative number number not encountered */    while (positive < size && a[positive] >= 0)        positive += 2;     /* Move forward the negative pointer till        positive number number not encountered */    while (negative < size && a[negative] <= 0)        negative += 2;     // Swap array elements to fix their position.    if (positive < size && negative < size) {        temp = a[positive];        a[positive] = a[negative];        a[negative] = temp;    }     /* Break from the while loop when any index    exceeds the size of the array */    else        break;    }} // Driver codepublic static void main(String args[]) {    int arr[] = {1, -3, 5, 6, -3, 6, 7, -4, 9, 10};    int n = arr.length;     rearrange(arr, n);    for (int i = 0; i < n; i++)    System.out.print(arr[i] + " ");}} /*This code is contributed by Nikita Tiwari.*/
# Python 3 program to rearrange# positive and negative numbers def rearrange(a, size) :         positive = 0    negative = 1     while (True) :                 # Move forward the positive        # pointer till negative number        # number not encountered        while (positive < size and a[positive] >= 0) :            positive = positive + 2         # Move forward the negative        # pointer till positive number        # number not encountered        while (negative < size and a[negative] <= 0) :            negative = negative + 2         # Swap array elements to fix        # their position.        if (positive < size and negative < size) :            temp = a[positive]            a[positive] = a[negative]            a[negative] = temp         # Break from the while loop when        # any index exceeds the size of        # the array        else :            break         # Driver codearr =[ 1, -3, 5, 6, -3, 6, 7, -4, 9, 10 ]n = len(arr) rearrange(arr, n)for i in range(0, n) :    print(arr[i], end = " ") # This code is contributed by Nikita Tiwari.
// C# program to rearrange positive// and negative numbersusing System; class GFG { // Function to rearrangestatic void rearrange(int []a, int size){int positive = 0, negative = 1, temp;     while (true) {     // Move forward the positive pointer till    // negative number number not encountered    while (positive < size && a[positive] >= 0)        positive += 2;     // Move forward the negative pointer till    // positive number number not encountered    while (negative < size && a[negative] <= 0)        negative += 2;     // Swap array elements to fix their position.    if (positive < size && negative < size) {        temp = a[positive];        a[positive] = a[negative];        a[negative] = temp;    }     // Break from the while loop when any    // index exceeds the size of the array    else        break;    }} // Driver Codepublic static void Main(String []args) {    int []arr = {1, -3, 5, 6, -3, 6, 7, -4, 9, 10};    int n = arr.Length;     rearrange(arr, n);    for (int i = 0; i < n; i++)    Console.Write(arr[i] + " ");}} // This code is contributed by Nitin Mittal.
<?php// PHP program to rearrange positive// and negative numbers function rearrange(&$a, $size){    $positive = 0;    $negative = 1;     while (true)    {         /* Move forward the positive        pointer till negative number        number not encountered */        while ($positive < $size &&               $a[$positive] >= 0)            $positive += 2;         /* Move forward the negative        pointer till positive number        number not encountered */        while ($negative < $size &&               $a[$negative] <= 0)            $negative += 2;         // Swap array elements to fix        // their position.        if ($positive < $size &&            $negative < $size)        {            $temp = $a[$positive];            $a[$positive] = $a[$negative];            $a[$negative] = $temp;        }                      /* Break from the while loop        when any index exceeds the        size of the array */        else            break;    }} // Driver code$arr = array( 1, -3, 5, 6, -3,              6, 7, -4, 9, 10 );$n = sizeof($arr); rearrange($arr, $n);for ($i = 0; $i < $n; $i++)    echo $arr[$i] ." "; // This code is contributed by ChitraNayal?>
<script> // Javascript  program to rearrange positive// and negative numbersfunction rearrange(a, size){    let  positive = 0;    let negative = 1;    let temp;     while (true)    {         // Move forward the positive        // pointer till negative number        // number not encountered        while (positive < size && a[positive] >= 0)            positive += 2;             // Move forward the negative pointer        // till positive number number not encountered        while (negative < size && a[negative] <= 0)            negative += 2;             // Swap array elements to fix their position.        if (positive < size && negative < size)        {            temp = a[positive];            a[positive] = a[negative];            a[negative] = temp;        }             // Break from the while loop when any index        // exceeds the size of the array        else            break;    }} // Driver codelet arr = [ 1, -3, 5, 6, -3,            6, 7, -4, 9, 10 ];let n = arr.length; rearrange(arr, n); for(let i = 0; i < n; i++)    document.write(arr[i] + " "); // This code is contributed by sravan kumar G </script>
Output: 
1 -3 5 -3 6 6 7 -4 9 10 
Time Complexity: O(n2), 
Auxiliary Space: O(1)
Lets explain the working of the code on the first example arr[] = {1, -3, 5, 6, -3, 6, 7, -4, 9, 10} We declare two variables positive and negative positive points to zeroth position and negative points to first position positive = 0 negative = 1 In the first iteration positive will move 4 places to fifth position as a[4] is less than zero and positive = 4. Negative will move 2 places and will point to fourth position as a[3]>0 we will swap positive and negative position values as they are less than size of array. After first iteration the array becomes arr[] = {1, -3, 5, -3, 6, 6, 7, -4, 9, 10}Now positive points at fourth position and negative points at third position In second iteration the positive value will move 6 places and its value will more than the size of the array. 
The negative pointer will move two steps forward and it will point to 5th position As the positive pointer value becomes greater than the array size we will not perform any swap operation and break out of the while loop. The final output will be arr[] = {1, -3, 5, -3, 6, 6, 7, -4, 9, 10}
An example where relative order is not maintained: { -1, -2, -3, -4, -5, 6, 7, 8 }; 
Another Approach :- The idea is to find a positive/negative element which is in incorrect place(i.e. positive at odd and negative at even place) and the then find the element of opposite sign which is also in incorrect position in the remaining array and then swap these two elements. 
Here is the implementation of the above idea.  
C++
Java
Python3
C#
Javascript
// C++ program to rearrange positive// and negative numbers#include<iostream>using namespace std; // Swap functionvoid swap(int* a, int i , int j){    int temp = a[i];    a[i] = a[j];    a[j] = temp;    return ;} // Print array functionvoid printArray(int* a, int n){    for(int i = 0; i < n; i++)        cout << a[i] << " ";    cout << endl;    return ;} // Driver codeint main(){    int arr[] = { 1, -3, 5, 6, -3, 6, 7, -4, 9, 10 };    int n = sizeof(arr)/sizeof(arr[0]);         //before modification    printArray(arr, n);     for(int i = 0; i < n; i++)    {        if(arr[i] >= 0 && i % 2 == 1)        {            // out of order positive element            for(int j = i + 1; j < n; j++)            {                if(arr[j] < 0 && j % 2 == 0)                {                    // find out of order negative                    // element in remaining array                    swap(arr, i, j);                    break ;                }            }        }        else if(arr[i] < 0 && i % 2 == 0)        {            // out of order negative element            for(int j = i + 1; j < n; j++)            {                if(arr[j] >= 0 && j % 2 == 1)                {                    // find out of order positive                    // element in remaining array                    swap(arr, i, j);                    break;                }            }        }    }         //after modification    printArray(arr, n);    return 0;} // This code is contributed by AnitAggarwal
// Java program to rearrange positive// and negative numbersimport java.io.*;import java.util.*; class GFG{     // Swap function    static void swap(int[] a, int i, int j)    {        int temp = a[i];        a[i] = a[j];        a[j] = temp;    }     // Print array function    static void printArray(int[] a, int n)    {        for (int i = 0; i < n; i++)            System.out.print(a[i] + " ");        System.out.println();    }     // Driver code    public static void main(String args[])    {        int[] arr = { 1, -3, 5, 6, -3, 6, 7, -4, 9, 10 };        int n = arr.length;                     //before modification        printArray(arr, n);         for (int i = 0; i < n; i++)        {            if (arr[i] >= 0 && i % 2 == 1)            {                // out of order positive element                for (int j = i + 1; j < n; j++)                {                    if (arr[j] < 0 && j % 2 == 0)                    {                        // find out of order negative                        // element in remaining array                        swap(arr, i, j);                        break ;                    }                }            }             else if (arr[i] < 0 && i % 2 == 0)            {                // out of order negative element                for (int j = i + 1; j < n; j++)                {                    if (arr[j] >= 0 && j % 2 == 1)                    {                        // find out of order positive                        // element in remaining array                        swap(arr, i, j);                        break;                    }                }            }        }         //after modification        printArray(arr, n);    }} // This code is contributed by rachana soma
# Python3 program to rearrange positive# and negative numbers # Print array functiondef printArray(a, n):    for i in a:        print(i, end = " ")    print()  # Driver codearr = [1, -3, 5, 6, -3, 6, 7, -4, 9, 10]n = len(arr) # before modificationprintArray(arr, n) for i in range(n):     if(arr[i] >= 0 and i % 2 == 1):         # out of order positive element        for j in range(i + 1, n):             if(arr[j] < 0 and j % 2 == 0):                                 # find out of order negative                # element in remaining array                arr[i], arr[j] = arr[j], arr[i]                break                 elif (arr[i] < 0 and i % 2 == 0):                 # out of order negative element        for j in range(i + 1, n):             if(arr[j] >= 0 and j % 2 == 1):                                 # find out of order positive                # element in remaining array                arr[i], arr[j] = arr[j], arr[i]                break # after modificationprintArray(arr, n); # This code is contributed# by mohit kumar
// C# program to rearrange positive// and negative numbersusing System; class GFG{     // Swap function    static void swap(int[] a, int i, int j)    {        int temp = a[i];        a[i] = a[j];        a[j] = temp;    }     // Print array function    static void printArray(int[] a, int n)    {        for (int i = 0; i < n; i++)            Console.Write(a[i] + " ");        Console.WriteLine();    }     // Driver code    public static void Main()    {        int[] arr = { 1, -3, 5, 6, -3, 6, 7, -4, 9, 10 };        int n = arr.Length;                     //before modification        printArray(arr, n);         for (int i = 0; i < n; i++)        {            if (arr[i] >= 0 && i % 2 == 1)            {                // out of order positive element                for (int j = i + 1; j < n; j++)                {                    if (arr[j] < 0 && j % 2 == 0)                    {                        // find out of order negative                        // element in remaining array                        swap(arr, i, j);                        break ;                    }                }            }             else if (arr[i] < 0 && i % 2 == 0)            {                // out of order negative element                for (int j = i + 1; j < n; j++)                {                    if (arr[j] >= 0 && j % 2 == 1)                    {                        // find out of order positive                        // element in remaining array                        swap(arr, i, j);                        break;                    }                }            }        }         // after modification        printArray(arr, n);    }} // This code is contributed by Akanksha Rai
<script> // Javascript program to rearrange positive// and negative numbers         // Swap function    function  swap(a,i,j)    {        let temp = a[i];        a[i] = a[j];        a[j] = temp;             }         // Print array function    function printArray(a,n)    {        for (let i = 0; i < n; i++)            document.write(a[i] + " ");        document.write("<br>");    }          // Driver code    let arr=[1, -3, 5, 6, -3, 6, 7, -4, 9, 10];    let n = arr.length;                      //before modification        printArray(arr, n);          for (let i = 0; i < n; i++)        {            if (arr[i] >= 0 && i % 2 == 1)            {                // out of order positive element                for (let j = i + 1; j < n; j++)                {                    if (arr[j] < 0 && j % 2 == 0)                    {                        // find out of order negative                        // element in remaining array                        swap(arr, i, j);                        break ;                    }                }            }              else if (arr[i] < 0 && i % 2 == 0)            {                // out of order negative element                for (let j = i + 1; j < n; j++)                {                    if (arr[j] >= 0 && j % 2 == 1)                    {                        // find out of order positive                        // element in remaining array                        swap(arr, i, j);                        break;                    }                }            }        }          //after modification        printArray(arr, n);              // This code is contributed by avanitrachhadiya2155     </script>
Output: 
1 -3 5 6 -3 6 7 -4 9 10 
1 -3 5 -3 6 6 7 -4 9 10 
Time Complexity: O(n2),
Auxiliary Space: O(1)This article is contributed by Ashish Madaan. 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 GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. 
nitin mittal
ukasp
theInjuredLion
mohit kumar 29
rachana soma
Akanksha_Rai
sravankumar8128
avanitrachhadiya2155
codewithmini
array-rearrange
Quick Sort
Arrays
Arrays
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.