Rearrange array such that all even | C ++ Program to implement the above approach ; Function to check if it the array can be rearranged such such that every even indices contains an even element ; Stores the count of even elements ; Traverse array to count even numbers ; If even_no_count exceeds count of even indices ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void checkPossible ( int a [ ] , int n ) { int even_no_count = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( a [ i ] % 2 == 0 ) even_no_count ++ ; } if ( n / 2 > even_no_count ) { cout << " No " << endl ; return ; } cout << " Yes " << endl ; int j = 0 ; for ( int i = 1 ; i < n ; i += 2 ) { if ( a [ i ] % 2 == 0 ) continue ; else { while ( j < n && a [ j ] % 2 != 0 ) j += 2 ; a [ i ] += a [ j ] ; a [ j ] = a [ i ] - a [ j ] ; a [ i ] -= a [ j ] ; } } for ( int i = 0 ; i < n ; i ++ ) { cout << a [ i ] << " ▁ " ; } } int main ( ) { int arr [ ] = { 2 , 3 , 4 , 5 , 6 , 7 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; checkPossible ( arr , n ) ; return 0 ; }