Positive elements at even and negative at odd positions ( Relative order not maintained ) | C ++ program to rearrange positive and negative numbers ; Swap function ; Print array function ; Driver code ; before modification ; out of order positive element ; find out of order negative element in remaining array ; out of order negative element ; find out of order positive element in remaining array ; after modification
#include <iostream> NEW_LINE using namespace std ; void swap ( int * a , int i , int j ) { int temp = a [ i ] ; a [ i ] = a [ j ] ; a [ j ] = temp ; return ; } void printArray ( int * a , int n ) { for ( int i = 0 ; i < n ; i ++ ) cout << a [ i ] << " ▁ " ; cout << endl ; return ; } int main ( ) { int arr [ ] = { 1 , -3 , 5 , 6 , -3 , 6 , 7 , -4 , 9 , 10 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; printArray ( arr , n ) ; for ( int i = 0 ; i < n ; i ++ ) { if ( arr [ i ] >= 0 && i % 2 == 1 ) { for ( int j = i + 1 ; j < n ; j ++ ) { if ( arr [ j ] < 0 && j % 2 == 0 ) { swap ( arr , i , j ) ; break ; } } } else if ( arr [ i ] < 0 && i % 2 == 0 ) { for ( int j = i + 1 ; j < n ; j ++ ) { if ( arr [ j ] >= 0 && j % 2 == 1 ) { swap ( arr , i , j ) ; break ; } } } } printArray ( arr , n ) ; return 0 ; }