Even numbers at even index and odd numbers at odd index in C++


In this problem, we are given an array arr[] of size n consisting of n/2 even values and n/2 odd values. Our task is to create a program to place even numbers at even index and odd numbers at odd index. 

Let’s take an example to understand the problem,

Input: arr[] = {5, 1, 6, 4, 3, 8}

Output: arr[] = {6, 1, 5, 4, 3, 8}

Solution Approach −

A solution would be traversing the array and then find the end number which is not at even position and replacing it with the next off place value. This is a promising solution but the solution can be made more efficient by using two indexes one for even and one for odd. If there is an element at even index which is not even and an odd element which is not at odd index, we will swap them otherwise increase both indices by two.

Program to illustrate the working of our solution,

Example

Live Demo

#include <iostream>
using namespace std;

void O_EReshuffle(int arr[], int n) {
   
   int oIndex = 1;
   int eIndex = 0;
   
   for(int i = 0; i < n; ) {
     
      while (eIndex < n && arr[eIndex] % 2 == 0)
         eIndex += 2;
         
      while (oIndex < n && arr[oIndex] % 2 == 1)
         oIndex += 2;
         
      if (eIndex < n && oIndex < n)
         swap (arr[eIndex], arr[oIndex]);
         
      else
         break;
   }
}

int main()
{
   int arr[] = { 5, 1, 6, 4, 3, 8 };
   int n = sizeof(arr) / sizeof(arr[0]);

   cout << "Array before Reshuffling: ";
   for(int i = 0; i < n ; i++){
      cout<<arr[i]<<"\t";
   }
   O_EReshuffle(arr, n);

   cout<<"\nArray after Reshuffling: ";
   for(int i = 0; i < n ; i++){
      cout<<arr[i]<<"\t";
   };

   return 0;
}

Output −

Array before Reshuffling: 5 1 6 4 3 8
Array after Reshuffling: 4 1 6 5 8 3

Updated on: 22-Jan-2021

804 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements