Given an array arr[] of N positive integers with an equal number of even and odd elements. The task is to use in-place swapping to interchange positions of even and odd elements in the array.
Examples:
Input: arr[] = {1, 3, 2, 4}
Output: 2 4 1 3
Explanation:
Before rearranging the given array, indices 0 and 1 had odd elements and indices 2 and 3 had even elements.
After rearrangement, array becomes {2, 4, 1, 3} where indices 0 and 1 have even elements and indices 2 and 3 have odd elements.
Input: arr[] = {2, 2, 1, 3}
Output: 1 3 2 2
Explanation:
Before rearranging the given array, indices 0 and 1 had even elements and indices 2 and 3 had odd elements.
After rearrangement, array becomes {1, 3, 2, 2} where indices 0 and 1 have odd elements and indices 2 and 3 have even elements.
Naive Approach: The simplest approach is to iterate over array elements using two loops, the outer loop picks each element of the array and the inner loop is to find the opposite parity element for the picked element and swap them. After swapping elements, mark the picked element as negative so as not to pick it again. Finally, make all elements positive and print the array.
Below is the implementation of the above approach:
C++
#include<bits/stdc++.h>
using namespace std;
void replace( int arr[], int n)
{
for ( int i = 0; i < n; i++)
{
for ( int j = i + 1; j < n; j++)
{
if (arr[i] >= 0 && arr[j] >= 0 &&
arr[i] % 2 == 0 &&
arr[j] % 2 != 0)
{
int tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
arr[j] = -arr[j];
break ;
}
else if (arr[i] >= 0 && arr[j] >= 0 &&
arr[i] % 2 != 0 &&
arr[j] % 2 == 0)
{
int tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
arr[j] = -arr[j];
break ;
}
}
}
for ( int i = 0; i < n; i++)
arr[i] = abs (arr[i]);
for ( int i = 0; i < n; i++)
cout << arr[i] << " " ;
}
int main()
{
int arr[] = { 1, 3, 2, 4 };
int n = sizeof (arr) / sizeof (arr[0]);
replace(arr,n);
}
|
Java
import java.util.*;
import java.lang.*;
class GFG {
static void replace( int [] arr)
{
int n = arr.length;
for ( int i = 0 ; i < n; i++) {
for ( int j = i + 1 ; j < n; j++) {
if (arr[i] >= 0
&& arr[j] >= 0
&& arr[i] % 2 == 0
&& arr[j] % 2 != 0 ) {
int tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
arr[j] = -arr[j];
break ;
}
else if (arr[i] >= 0
&& arr[j] >= 0
&& arr[i] % 2 != 0
&& arr[j] % 2 == 0 ) {
int tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
arr[j] = -arr[j];
break ;
}
}
}
for ( int i = 0 ; i < n; i++)
arr[i] = Math.abs(arr[i]);
for ( int i = 0 ; i < n; i++)
System.out.print(arr[i] + " " );
}
public static void main(String[] args)
{
int [] arr = { 1 , 3 , 2 , 4 };
replace(arr);
}
}
|
Python3
def replace(arr, n):
for i in range (n):
for j in range (i + 1 , n):
if (arr[i] > = 0 and
arr[j] > = 0 and
arr[i] % 2 = = 0 and
arr[j] % 2 ! = 0 ):
tmp = arr[i]
arr[i] = arr[j]
arr[j] = tmp
arr[j] = - arr[j]
break
elif (arr[i] > = 0 and
arr[j] > = 0 and
arr[i] % 2 ! = 0 and
arr[j] % 2 = = 0 ):
tmp = arr[i]
arr[i] = arr[j]
arr[j] = tmp
arr[j] = - arr[j]
break
for i in range (n):
arr[i] = abs (arr[i])
for i in range (n):
print (arr[i], end = " " )
if __name__ = = "__main__" :
arr = [ 1 , 3 , 2 , 4 ]
n = len (arr)
replace(arr, n)
|
C#
using System;
class GFG{
static void replace( int [] arr)
{
int n = arr.Length;
for ( int i = 0; i < n; i++)
{
for ( int j = i + 1; j < n; j++)
{
if (arr[i] >= 0 &&
arr[j] >= 0 &&
arr[i] % 2 == 0 &&
arr[j] % 2 != 0)
{
int tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
arr[j] = -arr[j];
break ;
}
else if (arr[i] >= 0 &&
arr[j] >= 0 &&
arr[i] % 2 != 0 &&
arr[j] % 2 == 0)
{
int tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
arr[j] = -arr[j];
break ;
}
}
}
for ( int i = 0; i < n; i++)
arr[i] = Math.Abs(arr[i]);
for ( int i = 0; i < n; i++)
Console.Write(arr[i] + " " );
}
public static void Main(String[] args)
{
int [] arr = { 1, 3, 2, 4 };
replace(arr);
}
}
|
Javascript
<script>
function replace(arr)
{
let n = arr.length;
for (let i = 0; i < n; i++) {
for (let j = i + 1; j < n; j++) {
if (arr[i] >= 0
&& arr[j] >= 0
&& arr[i] % 2 == 0
&& arr[j] % 2 != 0) {
let tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
arr[j] = -arr[j];
break ;
}
else if (arr[i] >= 0
&& arr[j] >= 0
&& arr[i] % 2 != 0
&& arr[j] % 2 == 0) {
let tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
arr[j] = -arr[j];
break ;
}
}
}
for (let i = 0; i < n; i++)
arr[i] = Math.abs(arr[i]);
for (let i = 0; i < n; i++)
document.write(arr[i] + " " );
}
let arr = [ 1, 3, 2, 4 ];
replace(arr);
</script>
|
Time Complexity: O(N2)
Auxiliary Space: O(1)
Efficient Approach: To optimize the above approach, the idea is to use Two Pointer Approach. Traverse the array by picking each element that is greater than 0 and search for the opposite parity element greater than 0 from the current index up to the end of the array. If found, swap the elements and multiply them with -1. Follow the below steps to solve the problem:
- Initialize the variables e and o with -1 that will store the currently found even and odd number respectively that is not yet taken.
- Traverse the given array over the range [0, N – 1] and do the following:
- Pick the element arr[i] if it is greater than 0.
- If arr[i] is even, increment o + 1 by 1 and find the next odd number that is not yet marked is found. Mark the current and the found number by multiplying them with -1 and swap them.
- If arr[i] is odd, increment e + 1 by 1 and find the next even number that is not yet marked is found. Mark the current and the found number by multiplying them with -1 and swap them.
- After traversing the whole array, multiply its elements with -1 to again make them positive and print that array.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
#define N 3
#define M 4
void swapEvenOdd( int arr[], int n)
{
int o = -1, e = -1;
for ( int i = 0; i < n; i++)
{
if (arr[i] < 0)
continue ;
int r = -1;
if (arr[i] % 2 == 0)
{
o++;
while (arr[o] % 2 == 0 || arr[o] < 0)
o++;
r = o;
}
else
{
e++;
while (arr[e] % 2 == 1 || arr[e] < 0)
e++;
r = e;
}
arr[i] *= -1;
arr[r] *= -1;
int tmp = arr[i];
arr[i] = arr[r];
arr[r] = tmp;
}
for ( int i = 0; i < n; i++)
{
cout << (-1 * arr[i]) << " " ;
}
}
int main()
{
int arr[] = { 1, 3, 2, 4 };
int n = sizeof (arr) / sizeof (arr[0]);
swapEvenOdd(arr, n);
}
|
Java
import java.io.*;
class GFG {
static void swapEvenOdd( int arr[])
{
int n = arr.length;
int o = - 1 , e = - 1 ;
for ( int i = 0 ; i < n; i++) {
if (arr[i] < 0 )
continue ;
int r = - 1 ;
if (arr[i] % 2 == 0 ) {
o++;
while (arr[o] % 2 == 0
|| arr[o] < 0 )
o++;
r = o;
}
else {
e++;
while (arr[e] % 2 == 1
|| arr[e] < 0 )
e++;
r = e;
}
arr[i] *= - 1 ;
arr[r] *= - 1 ;
int tmp = arr[i];
arr[i] = arr[r];
arr[r] = tmp;
}
for ( int i = 0 ; i < n; i++) {
System.out.print(
(- 1 * arr[i]) + " " );
}
}
public static void main(String[] args)
{
int arr[] = { 1 , 3 , 2 , 4 };
swapEvenOdd(arr);
}
}
|
Python3
def swapEvenOdd(arr):
n = len (arr)
o = - 1
e = - 1
for i in range (n):
if (arr[i] < 0 ):
continue
r = - 1
if (arr[i] % 2 = = 0 ):
o + = 1
while (arr[o] % 2 = = 0 or
arr[o] < 0 ):
o + = 1
r = o
else :
e + = 1
while (arr[e] % 2 = = 1 or
arr[e] < 0 ):
e + = 1
r = e
arr[i] * = - 1
arr[r] * = - 1
tmp = arr[i]
arr[i] = arr[r]
arr[r] = tmp
for i in range (n):
print (( - 1 * arr[i]), end = " " )
if __name__ = = '__main__' :
arr = [ 1 , 3 , 2 , 4 ]
swapEvenOdd(arr)
|
C#
using System;
class GFG{
static void swapEvenOdd( int []arr)
{
int n = arr.Length;
int o = -1, e = -1;
for ( int i = 0; i < n; i++)
{
if (arr[i] < 0)
continue ;
int r = -1;
if (arr[i] % 2 == 0)
{
o++;
while (arr[o] % 2 == 0 ||
arr[o] < 0)
o++;
r = o;
}
else
{
e++;
while (arr[e] % 2 == 1 ||
arr[e] < 0)
e++;
r = e;
}
arr[i] *= -1;
arr[r] *= -1;
int tmp = arr[i];
arr[i] = arr[r];
arr[r] = tmp;
}
for ( int i = 0; i < n; i++)
{
Console.Write((-1 * arr[i]) + " " );
}
}
public static void Main(String[] args)
{
int []arr = { 1, 3, 2, 4 };
swapEvenOdd(arr);
}
}
|
Javascript
<script>
function swapEvenOdd(arr, n)
{
let o = -1, e = -1;
for (let i = 0; i < n; i++)
{
if (arr[i] < 0)
continue ;
let r = -1;
if (arr[i] % 2 == 0)
{
o++;
while (arr[o] % 2 == 0 || arr[o] < 0)
o++;
r = o;
}
else
{
e++;
while (arr[e] % 2 == 1 || arr[e] < 0)
e++;
r = e;
}
arr[i] *= -1;
arr[r] *= -1;
let tmp = arr[i];
arr[i] = arr[r];
arr[r] = tmp;
}
for (let i = 0; i < n; i++)
{
document.write((-1 * arr[i]) + " " );
}
}
let arr = [ 1, 3, 2, 4 ];
let n = arr.length;
swapEvenOdd(arr, n);
</script>
|
Time Complexity: O(N)
Auxiliary Space: O(N)
Efficient Approach 2 :
Another way to do this would be by using a stack. Follow the below steps:
- Take element at index from the array arr[] and push to a stack
- Iterate arr[] from index i = 1 to end and do the following:
- If arr[i] and item on top of the stack are not both even or not both odd, pop and swap
- Else push item to stack
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
void swapEvenOdd( int arr[], int N)
{
stack<pair< int , int > > stack;
stack.push({ 0, arr[0] });
for ( int i = 1; i < N; i++)
{
if (!stack.empty())
{
if (arr[i] % 2 != stack.top().second % 2)
{
pair< int , int > pop = stack.top();
stack.pop();
int index = pop.first, val = pop.second;
arr[index] = arr[i];
arr[i] = val;
}
else
stack.push({ i, arr[i] });
}
else
stack.push({ i, arr[i] });
}
for ( int i = 0; i < N; i++)
cout << arr[i] << " " ;
}
int main()
{
int arr[] = { 1, 3, 2, 4 };
int N = sizeof (arr) / sizeof (arr[0]);
swapEvenOdd(arr, N);
return 0;
}
|
Java
import java.io.*;
import java.lang.*;
import java.util.*;
class GFG {
static void swapEvenOdd( int arr[], int N)
{
Stack< int []> stack = new Stack<>();
stack.push( new int [] { 0 , arr[ 0 ] });
for ( int i = 1 ; i < N; i++)
{
if (!stack.isEmpty())
{
if (arr[i] % 2 != stack.peek()[ 1 ] % 2 )
{
int pop[] = stack.pop();
int index = pop[ 0 ], val = pop[ 1 ];
arr[index] = arr[i];
arr[i] = val;
}
else
stack.push( new int [] { i, arr[i] });
}
else
stack.push( new int [] { i, arr[i] });
}
for ( int i = 0 ; i < N; i++)
System.out.print(arr[i] + " " );
}
public static void main(String[] args)
{
int arr[] = { 1 , 3 , 2 , 4 };
int N = arr.length;
swapEvenOdd(arr, N);
}
}
|
Python3
def swapEvenOdd(arr):
stack = []
stack.append(( 0 , arr[ 0 ],))
for i in range ( 1 , len (arr)):
if stack:
if arr[i] % 2 ! = stack[ - 1 ][ 1 ] % 2 :
index, val = stack.pop( - 1 )
arr[index] = arr[i]
arr[i] = val
else :
stack.append((i, arr[i],))
else :
stack.append((i, arr[i],))
return arr
if __name__ = = '__main__' :
arr = [ 1 , 3 , 2 , 4 ]
print (swapEvenOdd(arr))
|
C#
using System;
using System.Collections.Generic;
public class GFG
{
static void swapEvenOdd( int []arr, int N) {
Stack< int []> stack = new Stack< int []>();
stack.Push( new int [] { 0, arr[0] });
for ( int i = 1; i < N; i++)
{
if (stack.Count != 0)
{
if (arr[i] % 2 != stack.Peek()[1] % 2)
{
int []pop = stack.Pop();
int index = pop[0], val = pop[1];
arr[index] = arr[i];
arr[i] = val;
}
else
stack.Push( new int [] { i, arr[i] });
}
else
stack.Push( new int [] { i, arr[i] });
}
for ( int i = 0; i < N; i++)
Console.Write(arr[i] + " " );
}
public static void Main(String[] args)
{
int []arr = { 1, 3, 2, 4 };
int N = arr.Length;
swapEvenOdd(arr, N);
}
}
|
Javascript
<script>
function swapEvenOdd(arr, N)
{
let stack = [];
stack.push([0, arr[0]]);
for (let i = 1; i < N; i++)
{
if (stack.length != 0)
{
if (arr[i] % 2 !=
stack[stack.length - 1][1] % 2)
{
let pop = stack.pop();
let index = pop[0], val = pop[1];
arr[index] = arr[i];
arr[i] = val;
}
else
stack.push([i, arr[i]]);
}
else
stack.push([i, arr[i]]);
}
for (let i = 0; i < N; i++)
document.write(arr[i] + " " );
}
let arr = [ 1, 3, 2, 4 ];
let N = arr.length;
swapEvenOdd(arr, N);
</script>
|
Time Complexity: O(N)
Auxiliary Space: O(N)
Feeling lost in the world of random DSA topics, wasting time without progress? It's time for a change! Join our DSA course, where we'll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 geeks!
Last Updated :
02 Mar, 2022
Like Article
Save Article