Rearrange array by interchanging positions of even and odd elements in the given array

02 Mar, 2022
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 3Explanation: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 2Explanation: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++
Java
Python3
C#
Javascript
// C++ program for the above approach#include<bits/stdc++.h>using namespace std; // Function to replace each even// element by odd and vice-versa// in a given arrayvoid replace(int arr[], int n){         // Traverse array    for(int i = 0; i < n; i++)    {        for(int j = i + 1; j < n; j++)        {                         // If current element is even            // then swap it with odd            if (arr[i] >= 0 && arr[j] >= 0 &&                arr[i] % 2 == 0 &&                arr[j] % 2 != 0)            {                                 // Perform Swap                int tmp = arr[i];                arr[i] = arr[j];                arr[j] = tmp;                 // Change the sign                arr[j] = -arr[j];                 break;            }             // If current element is odd            // then swap it with even            else if (arr[i] >= 0 && arr[j] >= 0 &&                     arr[i] % 2 != 0 &&                     arr[j] % 2 == 0)            {                                 // Perform Swap                int tmp = arr[i];                arr[i] = arr[j];                arr[j] = tmp;                 // Change the sign                arr[j] = -arr[j];                 break;            }        }    }     // Marked element positive    for(int i = 0; i < n; i++)        arr[i] = abs(arr[i]);     // Print final array    for(int i = 0; i < n; i++)         cout << arr[i] << " ";} // Driver Codeint main(){         // Given array arr[]    int arr[] = { 1, 3, 2, 4 };    int n = sizeof(arr) / sizeof(arr[0]);         // Function Call    replace(arr,n);} // This code is contributed by SURENDRA_GANGWAR
// Java program for the above approachimport java.util.*;import java.lang.*; class GFG {     // Function to replace each even    // element by odd and vice-versa    // in a given array    static void replace(int[] arr)    {        // Stores length of array        int n = arr.length;         // Traverse array        for (int i = 0; i < n; i++) {             for (int j = i + 1; j < n; j++) {                 // If current element is even                // then swap it with odd                if (arr[i] >= 0                    && arr[j] >= 0                    && arr[i] % 2 == 0                    && arr[j] % 2 != 0) {                     // Perform Swap                    int tmp = arr[i];                    arr[i] = arr[j];                    arr[j] = tmp;                     // Change the sign                    arr[j] = -arr[j];                     break;                }                 // If current element is odd                // then swap it with even                else if (arr[i] >= 0                         && arr[j] >= 0                         && arr[i] % 2 != 0                         && arr[j] % 2 == 0) {                     // Perform Swap                    int tmp = arr[i];                    arr[i] = arr[j];                    arr[j] = tmp;                     // Change the sign                    arr[j] = -arr[j];                     break;                }            }        }         // Marked element positive        for (int i = 0; i < n; i++)            arr[i] = Math.abs(arr[i]);         // Print final array        for (int i = 0; i < n; i++)            System.out.print(arr[i] + " ");    }     // Driver Code    public static void main(String[] args)    {        // Given array arr[]        int[] arr = { 1, 3, 2, 4 };         // Function Call        replace(arr);    }}
# Python3 program for the# above approach # Function to replace each even# element by odd and vice-versa# in a given arraydef replace(arr,  n):     # Traverse array    for i in range(n):        for j in range(i + 1, n):             # If current element is            # even then swap it with odd            if (arr[i] >= 0 and                arr[j] >= 0 and                arr[i] % 2 == 0 and                arr[j] % 2 != 0):                 # Perform Swap                tmp = arr[i]                arr[i] = arr[j]                arr[j] = tmp                 # Change the sign                arr[j] = -arr[j]                 break             # If current element is odd            # then swap it with even            elif (arr[i] >= 0 and                  arr[j] >= 0 and                  arr[i] % 2 != 0 and                  arr[j] % 2 == 0):                 # Perform Swap                tmp = arr[i]                arr[i] = arr[j]                arr[j] = tmp                 # Change the sign                arr[j] = -arr[j]                 break     # Marked element positive    for i in range(n):        arr[i] = abs(arr[i])     # Print final array    for i in range(n):        print(arr[i], end = " ") # Driver Codeif __name__ == "__main__":     # Given array arr[]    arr = [1, 3, 2, 4]    n = len(arr)     # Function Call    replace(arr, n) # This code is contributed by Chitranayal
// C# program for the above approachusing System; class GFG{     // Function to replace each even// element by odd and vice-versa// in a given arraystatic void replace(int[] arr){         // Stores length of array    int n = arr.Length;     // Traverse array    for(int i = 0; i < n; i++)    {        for(int j = i + 1; j < n; j++)        {                         // If current element is even            // then swap it with odd            if (arr[i] >= 0 &&                arr[j] >= 0 &&                arr[i] % 2 == 0 &&                arr[j] % 2 != 0)            {                                 // Perform Swap                int tmp = arr[i];                arr[i] = arr[j];                arr[j] = tmp;                                 // Change the sign                arr[j] = -arr[j];                 break;            }             // If current element is odd            // then swap it with even            else if (arr[i] >= 0 &&                     arr[j] >= 0 &&                     arr[i] % 2 != 0 &&                     arr[j] % 2 == 0)            {                                 // Perform Swap                int tmp = arr[i];                arr[i] = arr[j];                arr[j] = tmp;                                 // Change the sign                arr[j] = -arr[j];                 break;            }        }    }     // Marked element positive    for(int i = 0; i < n; i++)        arr[i] = Math.Abs(arr[i]);     // Print readonly array    for(int i = 0; i < n; i++)        Console.Write(arr[i] + " ");} // Driver Codepublic static void Main(String[] args){         // Given array []arr    int[] arr = { 1, 3, 2, 4 };     // Function Call    replace(arr);}} // This code is contributed by Rajput-Ji
<script>// Javascript program to implement// the above approach     // Function to replace each even    // element by odd and vice-versa    // in a given array    function replace(arr)    {        // Stores length of array        let n = arr.length;          // Traverse array        for (let i = 0; i < n; i++) {              for (let j = i + 1; j < n; j++) {                  // If current element is even                // then swap it with odd                if (arr[i] >= 0                    && arr[j] >= 0                    && arr[i] % 2 == 0                    && arr[j] % 2 != 0) {                      // Perform Swap                    let tmp = arr[i];                    arr[i] = arr[j];                    arr[j] = tmp;                      // Change the sign                    arr[j] = -arr[j];                      break;                }                  // If current element is odd                // then swap it with even                else if (arr[i] >= 0                         && arr[j] >= 0                         && arr[i] % 2 != 0                         && arr[j] % 2 == 0) {                      // Perform Swap                    let tmp = arr[i];                    arr[i] = arr[j];                    arr[j] = tmp;                      // Change the sign                    arr[j] = -arr[j];                      break;                }            }        }          // Marked element positive        for (let i = 0; i < n; i++)            arr[i] = Math.abs(arr[i]);          // Print final array        for (let i = 0; i < n; i++)            document.write(arr[i] + " ");    }      // Driver Code                 // Given array arr[]        let arr = [ 1, 3, 2, 4 ];          // Function Call        replace(arr);   </script>
2 4 1 3 
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.
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++
Java
Python3
C#
Javascript
// C++ program for the above approach#include <bits/stdc++.h>using namespace std;#define N 3#define M 4 // Function to replace odd elements// with even elements and vice versavoid swapEvenOdd(int arr[], int n){    int o = -1, e = -1;     // Traverse the given array    for(int i = 0; i < n; i++)    {                 // If arr[i] is visited        if (arr[i] < 0)            continue;         int r = -1;         if (arr[i] % 2 == 0)        {            o++;                         // Find the next odd element            while (arr[o] % 2 == 0 || arr[o] < 0)                o++;                             r = o;        }        else        {            e++;                         // Find next even element            while (arr[e] % 2 == 1 || arr[e] < 0)                e++;                             r = e;        }         // Mark them visited        arr[i] *= -1;        arr[r] *= -1;         // Swap them        int tmp = arr[i];        arr[i] = arr[r];        arr[r] = tmp;    }     // Print the final array    for(int i = 0; i < n; i++)    {        cout << (-1 * arr[i]) << " ";    }} // Driver Codeint main(){         // Given array arr[]    int arr[] = { 1, 3, 2, 4 };         // Length of the array    int n = sizeof(arr) / sizeof(arr[0]);         // Function Call    swapEvenOdd(arr, n);} // This code is contributed by Rajput-Ji
// Java program for the above approach import java.io.*; class GFG {     // Function to replace odd elements    // with even elements and vice versa    static void swapEvenOdd(int arr[])    {        // Length of the array        int n = arr.length;         int o = -1, e = -1;         // Traverse the given array        for (int i = 0; i < n; i++) {             // If arr[i] is visited            if (arr[i] < 0)                continue;             int r = -1;             if (arr[i] % 2 == 0) {                o++;                 // Find the next odd element                while (arr[o] % 2 == 0                       || arr[o] < 0)                    o++;                r = o;            }            else {                e++;                 // Find next even element                while (arr[e] % 2 == 1                       || arr[e] < 0)                    e++;                r = e;            }             // Mark them visited            arr[i] *= -1;            arr[r] *= -1;             // Swap them            int tmp = arr[i];            arr[i] = arr[r];            arr[r] = tmp;        }         // Print the final array        for (int i = 0; i < n; i++) {            System.out.print(                (-1 * arr[i]) + " ");        }    }     // Driver Code    public static void main(String[] args)    {        // Given array arr[]        int arr[] = { 1, 3, 2, 4 };         // Function Call        swapEvenOdd(arr);    }}
# Python3 program for the above approach # Function to replace odd elements# with even elements and vice versadef swapEvenOdd(arr):         # Length of the array    n = len(arr)     o = -1    e = -1     # Traverse the given array    for i in range(n):                 # If arr[i] is visited        if (arr[i] < 0):            continue         r = -1         if (arr[i] % 2 == 0):            o += 1             # Find the next odd element            while (arr[o] % 2 == 0 or                   arr[o] < 0):                o += 1                             r = o        else:            e += 1             # Find next even element            while (arr[e] % 2 == 1 or                   arr[e] < 0):                e += 1                             r = e         # Mark them visited        arr[i] *= -1        arr[r] *= -1         # Swap them        tmp = arr[i]        arr[i] = arr[r]        arr[r] = tmp     # Print the final array    for i in range(n):        print((-1 * arr[i]), end = " ") # Driver Codeif __name__ == '__main__':         # Given array arr    arr = [ 1, 3, 2, 4 ]     # Function Call    swapEvenOdd(arr) # This code is contributed by Amit Katiyar
// C# program for the above approachusing System; class GFG{ // Function to replace odd elements// with even elements and vice versastatic void swapEvenOdd(int []arr){         // Length of the array    int n = arr.Length;     int o = -1, e = -1;     // Traverse the given array    for(int i = 0; i < n; i++)    {                 // If arr[i] is visited        if (arr[i] < 0)            continue;         int r = -1;         if (arr[i] % 2 == 0)        {            o++;                         // Find the next odd element            while (arr[o] % 2 == 0 ||                   arr[o] < 0)                o++;                             r = o;        }        else        {            e++;             // Find next even element            while (arr[e] % 2 == 1 ||                   arr[e] < 0)                e++;                             r = e;        }         // Mark them visited        arr[i] *= -1;        arr[r] *= -1;         // Swap them        int tmp = arr[i];        arr[i] = arr[r];        arr[r] = tmp;    }     // Print the readonly array    for(int i = 0; i < n; i++)    {        Console.Write((-1 * arr[i]) + " ");    }} // Driver Codepublic static void Main(String[] args){         // Given array []arr    int []arr = { 1, 3, 2, 4 };     // Function Call    swapEvenOdd(arr);}} // This code is contributed by Amit Katiyar
<script>// JavaScript program for the above approach  // Function to replace odd elements// with even elements and vice versafunction swapEvenOdd(arr, n){    let o = -1, e = -1;     // Traverse the given array    for(let i = 0; i < n; i++)    {                 // If arr[i] is visited        if (arr[i] < 0)            continue;         let r = -1;         if (arr[i] % 2 == 0)        {            o++;                         // Find the next odd element            while (arr[o] % 2 == 0 || arr[o] < 0)                o++;                             r = o;        }        else        {            e++;                         // Find next even element            while (arr[e] % 2 == 1 || arr[e] < 0)                e++;                             r = e;        }         // Mark them visited        arr[i] *= -1;        arr[r] *= -1;         // Swap them        let tmp = arr[i];        arr[i] = arr[r];        arr[r] = tmp;    }     // Print the final array    for(let i = 0; i < n; i++)    {        document.write((-1 * arr[i]) + " ");    }} // Driver Code         // Given array arr[]    let arr = [ 1, 3, 2, 4 ];         // Length of the array    let n = arr.length;         // Function Call    swapEvenOdd(arr, n);  //This code is contributed by Mayank Tyagi</script>
2 4 1 3 
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 stackIterate 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 swapElse push item to stack
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 swapElse push item to stack
If arr[i] and item on top of the stack are not both even or not both odd, pop and swapElse push item to stack
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++
Java
Python3
C#
Javascript
// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to replace odd elements// with even elements and vice versavoid swapEvenOdd(int arr[], int N){  stack<pair<int, int> > stack;   // Push the first element to stack  stack.push({ 0, arr[0] });   // iterate the array and swap even and odd  for (int i = 1; i < N; i++)  {    if (!stack.empty())    {      if (arr[i] % 2 != stack.top().second % 2)      {         // pop and swap        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] });  }   // print the arr[]  for (int i = 0; i < N; i++)    cout << arr[i] << " ";} // Driven Programint main(){   // Given array arr[]  int arr[] = { 1, 3, 2, 4 };   // Stores the length of array  int N = sizeof(arr) / sizeof(arr[0]);   // Function Call  swapEvenOdd(arr, N);  return 0;} // This code is contributed by Kingash.
// Java program for the above approachimport java.io.*;import java.lang.*;import java.util.*; class GFG {   // Function to replace odd elements  // with even elements and vice versa  static void swapEvenOdd(int arr[], int N)  {     Stack<int[]> stack = new Stack<>();     // Push the first element to stack    stack.push(new int[] { 0, arr[0] });     // iterate the array and swap even and odd    for (int i = 1; i < N; i++)    {      if (!stack.isEmpty())      {        if (arr[i] % 2 != stack.peek()[1] % 2)        {           // pop and swap          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] });    }     // print the arr[]    for (int i = 0; i < N; i++)      System.out.print(arr[i] + " ");  }   // Driver code  public static void main(String[] args)  {     // Given array arr    int arr[] = { 1, 3, 2, 4 };     // length of the arr    int N = arr.length;     // Function Call    swapEvenOdd(arr, N);  }} // This code is contributed by Kingash.
# Python3 program for the above approach # Function to replace odd elements# with even elements and vice versadef swapEvenOdd(arr):    stack = []         # Push the first element to stack    stack.append((0, arr[0],))         # iterate the array and swap even and odd    for i in range(1, len(arr)):        if stack:            if arr[i]%2 != stack[-1][1]%2:                #pop and swap                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 # Driver Codeif __name__ == '__main__':         # Given array arr    arr = [ 1, 3, 2, 4 ]     # Function Call    print(swapEvenOdd(arr)) # This code is contributed by Arunabha Choudhury
// C# program for the above approachusing System;using System.Collections.Generic;public class GFG{   // Function to replace odd elements  // with even elements and vice versa  static void swapEvenOdd(int []arr, int N) {     Stack<int[]> stack = new Stack<int[]>();     // Push the first element to stack    stack.Push(new int[] { 0, arr[0] });     // iterate the array and swap even and odd    for (int i = 1; i < N; i++)    {      if (stack.Count != 0)      {        if (arr[i] % 2 != stack.Peek()[1] % 2)        {           // pop and swap          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] });    }     // print the []arr    for (int i = 0; i < N; i++)      Console.Write(arr[i] + " ");  }   // Driver code  public static void Main(String[] args)  {     // Given array arr    int []arr = { 1, 3, 2, 4 };     // length of the arr    int N = arr.Length;     // Function Call    swapEvenOdd(arr, N);  }} // This code is contributed by gauravrajput1
<script> // Javascript program for the above approach // Function to replace odd elements// with even elements and vice versafunction swapEvenOdd(arr, N){    let stack = [];      // Push the first element to stack    stack.push([0, arr[0]]);      // Iterate the array and swap even and odd    for(let i = 1; i < N; i++)    {        if (stack.length != 0)        {            if (arr[i] % 2 !=                stack[stack.length - 1][1] % 2)            {                             // pop and swap                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]]);    }      // print the arr[]    for(let i = 0; i < N; i++)        document.write(arr[i] + " ");} // Driver code // Given array arrlet arr = [ 1, 3, 2, 4 ]; // Length of the arrlet N = arr.length; // Function CallswapEvenOdd(arr, N); // This code is contributed by avanitrachhadiya2155 </script>
[4, 2, 3, 1]
Time Complexity: O(N)Auxiliary Space: O(N)
SURENDRA_GANGWAR
ukasp
Rajput-Ji
amit143katiyar
arunabhachoudhury24
Kingash
avijitmondal1998
mayanktyagi1709
avanitrachhadiya2155
koulayush
GauravRajput1
simranarora5sos
array-rearrange
array-traversal-question
Google
interview-preparation
two-pointer-algorithm
Arrays
School Programming
Searching
Google
two-pointer-algorithm
Arrays
Searching
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Maximum and minimum of an array using minimum number of comparisons
Top 50 Array Coding Problems for Interviews
Multidimensional Arrays in Java
Stack Data Structure (Introduction and Program)
Linear Search
Python Dictionary
Reverse a string in Java
Introduction To PYTHON
Interfaces in Java
Inheritance in C++