Arrays: Rearrange the array with one positive and one negative number.

Problem Statement:

Given an unsorted array with combination of positive and negative integers.

you need to re arrange them in one positive and one negative format.

Any extra +ve or -ve numbers should come at the end.

Solution:

This problem can be solved in number of different ways.

In this article we shall discuss a easy approach, below are the steps:

1. Keep the -ve elements in odd index
2. Keep the +ve elements in even index.
3. We get the solution

Solution in C++

#include <vector>    
#include <algorithm>  
//visit www.ProDeveloperTutorial.com for 450+ solved questions  
#include <iostream>    
#include <queue>

using namespace std;  

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

void toggle_elements(int arr[], int n)
{
    int negative = 0;
    int positive = 1;
    int i = 0;

    // keep negative elements first on odd index
    while( i < n )
    {
        if(arr[i] < 0 && negative <n)
        {
            swap(&arr[i], & arr[negative]);
            negative += 2;
        }
        i++;
    }

    i=0;
    // keep positive elements  on even index
    while(i<n)
    {
        if(arr[i] >= 0 && positive <n)
        {
            swap(&arr[i], & arr[positive]);
            positive += 2;
        }
        i++;
    }

//print the array

    for(int i=0; i<n; i++)
    {
        cout<<arr[i]<<" ";
    }
    cout<<endl;
}

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

Output:

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

 

 

 

 

Write a Comment

Leave a Comment

Your email address will not be published. Required fields are marked *