5/29/2018 - 8:56 PM

Positive elements at even and negative at odd positions, approach 2

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 and the relative order of the elements must be maintained. There can be unequal number of positive and negative values and the extra values have to left as it is.


Input : arr[] = {1, -3, 5, 6, -3, 6, 7, -4, 9, 10} Output : arr[] = {1, -3, 5, -3, 6, 6, 7, -4, 9, 10}

Idea: 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

#include <iostream>
using namespace std;

int rearrange(int a[],int n){
    int pos=0,neg=1;
        while (a[pos] > 0)
        while (a[neg] < 0)
        if (pos<n && neg <n)
            swap(a[pos], a[neg]);


int main(){
    int n;
    cout << "No.of elements \n";
    cin >> n;
    int a[n];
    cout << "Enter the elements \n";
    for (int i = 0;i<n;i++)
        cin >> a[i];
    for (int i = 0;i<n;i++)
        cout << a[i] << "  ";