An array contains both positive and negative numbers in random order. Rearrange the array elements so that positive and negative numbers are placed alternatively. A number of positive and negative numbers need not be equal. If there are more positive numbers they appear at the end of the array. If there are more negative numbers, they too appear at the end of the array.
Example:
Input: [-1, 2, -3, 4, 5, 6, -7, 8, 9]
Output:[9, -7, 8, -3, 5, -1, 2, 4, 6]Input: [-1, 3, -2, -4, 7, -5]
Output:[7, -2, 3, -5, -1, -4]
Note: The partition process in this approach changes the relative order of elements. I.e. the order of the appearance of elements is not maintained with this approach. See this for maintaining the order of appearance of elements in this problem.
Approach:
The solution is to first separate positive and negative numbers using the partition process of QuickSort. In the partition process, consider 0 as the value of the pivot element so that all negative numbers are placed before positive numbers. Once negative and positive numbers are separated, we start from the first negative number and first positive number and swap every alternate negative number with the next positive number.
Below is the implementation of above idea:
C++
| // A C++ program to put positive// numbers at even indexes (0, 2, 4,..) // and negative numbers at odd // indexes (1, 3, 5, ..)#include <iostream>usingnamespacestd;classGFG{    public:    voidrearrange(int[],int);    voidswap(int*,int*);    voidprintArray(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, ..).voidGFG :: rearrange(intarr[], intn){    // 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.    inti = -1;    for(intj = 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    intpos = 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 elementsvoidGFG :: swap(int*a, int*b){    inttemp = *a;    *a = *b;    *b = temp;}// A utility function to print an arrayvoidGFG :: printArray(intarr[], intn){    for(inti = 0; i < n; i++)        cout << arr[i] << " ";}// Driver Codeintmain() {    intarr[] = {-1, 2, -3, 4,                   5, 6, -7, 8, 9};    intn = sizeof(arr) / sizeof(arr[0]);    GFG test;    test.rearrange(arr, n);    test.printArray(arr, n);    return0;}// 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 <stdio.h>// prototype for swapvoidswap(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, ..).voidrearrange(intarr[], intn){    // 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.    inti = -1;    for(intj = 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    intpos = 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 elementsvoidswap(int*a, int*b){    inttemp = *a;    *a = *b;    *b = temp;}// A utility function to print an arrayvoidprintArray(intarr[], intn){    for(inti = 0; i < n; i++)        printf("%4d ", arr[i]);}// Driver program to test above functionsintmain(){    intarr[] = {-1, 2, -3, 4,                   5, 6, -7, 8, 9};    intn = sizeof(arr)/sizeof(arr[0]);    rearrange(arr, n);    printArray(arr, n);    return0;} | 
Java
| // A JAVA program to put positive numbers at even indexes// (0, 2, 4,..) and negative numbers at odd indexes (1, 3,// 5, ..)importjava.io.*;classAlternate {    // 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, ..).    staticvoidrearrange(intarr[], intn)    {        // 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.        inti = -1, temp = 0;        for(intj = 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        intpos = 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    staticvoidprintArray(intarr[], intn)    {        for(inti = 0; i < n; i++)            System.out.print(arr[i] + "   ");    }    /*Driver function to check for above functions*/    publicstaticvoidmain (String[] args)    {        intarr[] = {-1, 2, -3, 4, 5, 6, -7, 8, 9};        intn = 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, ..).defrearrange(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    forj inrange(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 andneg < pos andarr[neg] < 0):        # swapping of arr        arr[neg], arr[pos] =arr[pos], arr[neg]        pos +=1        neg +=2# A utility function to print an arraydefprintArray(arr, n):        fori inrange(n):        print(arr[i],end=" ") # Driver program to test above functionsarr =[-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, ..)usingSystem;classAlternate {    // 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, ..).    staticvoidrearrange(int[] arr, intn)    {        // 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.        inti = -1, temp = 0;        for(intj = 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        intpos = 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    staticvoidprintArray(int[] arr, intn)    {        for(inti = 0; i < n; i++)            Console.Write(arr[i] + " ");    }    /*Driver function to check for above functions*/    publicstaticvoidMain()    {        int[] arr = { -1, 2, -3, 4, 5, 6, -7, 8, 9 };        intn = arr.Length;        rearrange(arr, n);        printArray(arr, n);    }}// This code is contributed by vt_m. | 
Javascript
| <script>// Javascript 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, ..).        functionrearrange(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.        let i = -1, temp = 0;        for(let 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        let 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    functionprintArray(arr,n)    {        for(let i = 0; i < n; i++)            document.write(arr[i] + "   ");    }    /*Driver function to check for above functions*/            let arr = [-1, 2, -3, 4, 5, 6, -7, 8, 9];        let n = arr.length;        rearrange(arr,n);        printArray(arr,n);    // This code is contributed by sravan kumar</script> | 
PHP
| <?php// A PHP 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, ..). functionrearrange(&$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= 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     $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 functionswap(&$a, &$b) {     $temp= $a;     $a= $b;     $b= $temp; } // A utility function to print an array functionprintArray(&$arr, $n) {     for($i= 0; $i< $n; $i++)         echo" ". $arr[$i] . " "; } // Driver Code$arr= array(-1, 2, -3, 4, 5, 6, -7, 8, 9); $n= count($arr); rearrange($arr, $n); printArray($arr, $n); // This code is contributed// by rathbhupendra?> | 
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.
Related Articles: 
Rearrange positive and negative numbers with constant extra space 
Move all negative elements to end in order with extra space allowed
This article is compiled by Abhay Rathi. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
If you like neveropen and would like to contribute, you can also write an article and mail your article to review-team@geeksforgeeks.org. See your article appearing on the neveropen main page and help other Geeks.
 
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!

 
                                    







