The Wayback Machine - https://web.archive.org/web/20240806182319/https://www.geeksforgeeks.org/even-numbers-even-index-odd-numbers-odd-index/
Open In App

Even numbers at even index and odd numbers at odd index

Last Updated : 31 Mar, 2023
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report

Given an array of size n containing equal number of odd and even numbers. The problem is to arrange the numbers in such a way that all the even numbers get the even index and odd numbers get the odd index. Required auxiliary space is O(1).
Examples : 

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

Input : arr[] = {10, 9, 7, 18, 13, 19, 4, 20, 21, 14}
Output : 10 9 18 7 20 19 4 13 14 21 

Source: Amazon Interview Experience | Set 410.
 

Recommended Practice

Approach : 

  • Start from the left and keep two index one for even position and other for odd positions.
  • Traverse these index from left.
  • At even position there should be even number and at odd positions, there should be odd number.
  • Whenever there is mismatch , we swap the values at odd and even index.

Below is the implementation of the above approach :

CPP




// C++ implementation to arrange
// odd and even numbers
#include <bits/stdc++.h>
using namespace std;
 
// function to arrange odd and even numbers
void arrangeOddAndEven(int arr[], int n)
{
   int oddInd = 1;
    int evenInd = 0;
    while (true)
    {
        while (evenInd < n && arr[evenInd] % 2 == 0)
            evenInd += 2;
             
        while (oddInd < n && arr[oddInd] % 2 == 1)
            oddInd += 2;
             
        if (evenInd < n && oddInd < n)
            swap (arr[evenInd], arr[oddInd]);
             
        else
            break;
    }
}
 
// function to print the array
void printArray(int arr[], int n)
{
    for (int i = 0; i < n; i++)
        cout << arr[i] << " ";
}
 
// Driver program to test above
int main()
{
    int arr[] = { 3, 6, 12, 1, 5, 8 };
    int n = sizeof(arr) / sizeof(arr[0]);
 
    cout << "Original Array: ";
    printArray(arr, n);
 
    arrangeOddAndEven(arr, n);
 
    cout << "\nModified Array: ";
    printArray(arr, n);
 
    return 0;
}


Java




// Java implementation to
// arrange odd and even numbers
 
import java.util.*;
import java.lang.*;
 
class GfG {
 
// function to arrange
// odd and even numbers
public static void arrangeOddAndEven(int arr[], int n)
{
    int oddInd = 1;
    int evenInd = 0;
    while (true)
    {
        while (evenInd < n && arr[evenInd] % 2 == 0)
            evenInd += 2;
             
        while (oddInd < n && arr[oddInd] % 2 == 1)
            oddInd += 2;
             
        if (evenInd < n && oddInd < n)
            {
                int temp = arr[evenInd];
                arr[evenInd] = arr[oddInd];
                arr[oddInd] = temp;
            }
             
        else
            break;
    }
}
 
// function to print the array
public static void printArray(int arr[], int n)
{
    for (int i = 0; i < n; i++)
        System.out.print(arr[i] + " ");
}
     
// Driver function
public static void main(String argc[]){
    int arr[] = { 3, 6, 12, 1, 5, 8 };
    int n = 6;
 
    System.out.print("Original Array: ");
    printArray(arr, n);
 
    arrangeOddAndEven(arr, n);
 
    System.out.print("\nModified Array: ");
    printArray(arr, n);
}
}
 
// This code is contributed by Sagar Shukla


Python3




     
# Python3 implementation to
# arrange odd and even numbers
 
def arrangeOddAndEven(arr,  n):
     
    oddInd = 1
    evenInd = 0
    while (True):
         
        while (evenInd < n and arr[evenInd] % 2 == 0):
            evenInd += 2
              
        while (oddInd < n and arr[oddInd] % 2 == 1):
            oddInd += 2
              
        if (evenInd < n and oddInd < n):
                temp = arr[evenInd]
                arr[evenInd] = arr[oddInd]
                arr[oddInd] = temp;
              
        else:
            break
  
# function to print the array
def printArray(arr,  n):
    for i in range(0,n):
        print(arr[i] , "",end="")
 
      
# Driver function
def main():
    arr = [ 3, 6, 12, 1, 5, 8 ]
    n = 6
  
    print("Original Array: ",end="")
    printArray(arr, n)
  
    arrangeOddAndEven(arr, n)
  
    print("\nModified Array: ",end="")
    printArray(arr, n)
     
if __name__ == '__main__':
    main()
# This code is contributed by 29AjayKumar


C#




// C# implementation to
// arrange odd and even numbers
using System;
 
class GFG {
 
    // function to arrange
    // odd and even numbers
    public static void arrangeOddAndEven(int[] arr, int n)
    {
     int oddInd = 1;
     int evenInd = 0;
    while (true)
    {
        while (evenInd < n && arr[evenInd] % 2 == 0)
            evenInd += 2;
              
        while (oddInd < n && arr[oddInd] % 2 == 1)
            oddInd += 2;
              
        if (evenInd < n && oddInd < n)
            {
                int temp = arr[evenInd];
                arr[evenInd] = arr[oddInd];
                arr[oddInd] = temp;
            }
              
        else
            break;
    }
    }
 
    // function to print the array
    public static void printArray(int[] arr, int n)
    {
        for (int i = 0; i < n; i++)
            Console.Write(arr[i] + " ");
    }
 
    // Driver function
    public static void Main()
    {
        int[] arr = { 3, 6, 12, 1, 5, 8 };
        int n = 6;
 
        Console.Write("Original Array: ");
        printArray(arr, n);
 
        arrangeOddAndEven(arr, n);
 
        Console.Write("\nModified Array: ");
        printArray(arr, n);
    }
}
 
// This code is contributed by Sam007


Javascript




<script>
 
// Javascript implementation to arrange
// odd and even numbers
 
// function to arrange odd and even numbers
function arrangeOddAndEven(arr, n)
{
    let oddInd = 1;
    let evenInd = 0;
    while (true)
    {
        while (evenInd < n && arr[evenInd] % 2 == 0)
            evenInd += 2;
             
        while (oddInd < n && arr[oddInd] % 2 == 1)
            oddInd += 2;
             
        if (evenInd < n && oddInd < n)
        {
            let temp;
            temp = arr[evenInd];
            arr[evenInd] = arr[oddInd];
            arr[oddInd] = temp;
        }   
        else
            break;
    }
}
 
// function to print the array
function printArray(arr, n)
{
    for (let i = 0; i < n; i++)
        document.write(arr[i] + " ");
}
 
// Driver program to test above
    let arr = [ 3, 6, 12, 1, 5, 8 ];
    let n = arr.length;
 
    document.write("Original Array: ");
    printArray(arr, n);
 
    arrangeOddAndEven(arr, n);
 
    document.write("<br>" + "Modified Array: ");
    printArray(arr, n);
 
// This code is contributed by Mayank Tyagi
 
</script>


Output

Original Array: 3 6 12 1 5 8 
Modified Array: 6 3 12 1 8 5 

Time Complexity: O(N), as we are using a loop to traverse N times.

Auxiliary Space: O(1), as we are not using any extra space.

Approach: Two-Pointer Swap

The steps to solve the problem using this approach are as follows:

  1. Initialize two pointers i and j to 0 and 1, respectively. These pointers will help us to keep track of the current indices of the elements in the array that we are processing.
  2. Loop through the array until i or j reaches the end of the array.
  3. If the element at index i is odd and the element at index j is even, swap them. This will ensure that the even number is moved to an even index and odd number is moved to an odd index.
  4. Increment both i and j by 2 to move them to the next odd and even index respectively.
  5. If the element at index i is already even, increment i by 2.
  6. Similarly, if the element at index j is already odd, increment j by 2.
  7. Once we have looped through the entire array, the even numbers will be at even indices and odd numbers will be at odd indices.
  8. Return the modified array.

C++




#include <iostream>
#include <vector>
 
using namespace std;
 
vector<int> arrange_array(vector<int> arr) {
    int i = 0;
    int j = 1;
    int n = arr.size();
    while (i < n && j < n) {
        if (arr[i] % 2 != 0 && arr[j] % 2 == 0) {
            swap(arr[i], arr[j]);
            i += 2;
            j += 2;
        }
        else {
            if (arr[i] % 2 == 0) {
                i += 2;
            }
            if (arr[j] % 2 != 0) {
                j += 2;
            }
        }
    }
    return arr;
}
 
int main() {
    // Example 1
    vector<int> arr1 = {3, 6, 12, 1, 5, 8};
    vector<int> arranged_arr1 = arrange_array(arr1);
    for (auto i : arranged_arr1) {
        cout << i << " ";
    }
    cout << endl;
 
    // Example 2
    vector<int> arr2 = {10, 9, 7, 18, 13, 19, 4, 20, 21, 14};
    vector<int> arranged_arr2 = arrange_array(arr2);
    for (auto i : arranged_arr2) {
        cout << i << " ";
    }
    cout << endl;
 
    return 0;
}


Java




import java.util.Arrays;
 
public class Main {
    public static void main(String[] args)
    {
        int[] arr1 = { 3, 6, 12, 1, 5, 8 };
        int[] arrangedArr1 = arrangeArray(arr1);
        System.out.println(Arrays.toString(arrangedArr1));
 
        int[] arr2
            = { 10, 9, 7, 18, 13, 19, 4, 20, 21, 14 };
        int[] arrangedArr2 = arrangeArray(arr2);
        System.out.println(Arrays.toString(arrangedArr2));
    }
 
    // Function to arrange the array such that odd numbers
    // are at odd indices and even numbers are at even
    // indices
    public static int[] arrangeArray(int[] arr)
    {
        int i = 0; // starting index for odd numbers
        int j = 1; // starting index for even numbers
        int n = arr.length; // length of the array
        while (i < n && j < n) {
            // if the number at i is odd and the number at j
            // is even, swap them and move to next pair of
            // indices
            if (arr[i] % 2 != 0 && arr[j] % 2 == 0) {
                int temp = arr[i];
                arr[i] = arr[j];
                arr[j] = temp;
                i += 2; // move to next odd index
                j += 2; // move to next even index
            }
            else {
                // if the number at i is even, move to next
                // odd index
                if (arr[i] % 2 == 0) {
                    i += 2;
                }
                // if the number at j is odd, move to next
                // even index
                if (arr[j] % 2 != 0) {
                    j += 2;
                }
            }
        }
        return arr; // return the arranged array
    }
}


Python3




def arrange_array(arr):
    i = 0
    j = 1
    n = len(arr)
    while i < n and j < n:
        if arr[i] % 2 != 0 and arr[j] % 2 == 0:
            arr[i], arr[j] = arr[j], arr[i]
            i += 2
            j += 2
        else:
            if arr[i] % 2 == 0:
                i += 2
            if arr[j] % 2 != 0:
                j += 2
    return arr
 
# Example 1
arr = [3, 6, 12, 1, 5, 8]
arranged_arr = arrange_array(arr)
print(arranged_arr)   # Output: [6, 3, 12, 1, 8, 5]
 
#Example
arr = [10, 9, 7, 18, 13, 19, 4, 20, 21, 14]
arranged_arr = arrange_array(arr)
print(arranged_arr)   # Output: [10, 9, 18, 7, 20, 19, 4, 13, 14, 21]


Javascript




function arrangeArray(arr) {
    let i = 0; // starting index for odd numbers
    let j = 1; // starting index for even numbers
    let n = arr.length; // length of the array
    while (i < n && j < n) {
        // if the number at i is odd and the number at j is even, swap them and move to next pair of indices
        if (arr[i] % 2 !== 0 && arr[j] % 2 === 0) {
            [arr[i], arr[j]] = [arr[j], arr[i]]; // swapping values
            i += 2; // move to next odd index
            j += 2; // move to next even index
        } else {
            // if the number at i is even, move to next odd index
            if (arr[i] % 2 === 0) {
                i += 2;
            }
            // if the number at j is odd, move to next even index
            if (arr[j] % 2 !== 0) {
                j += 2;
            }
        }
    }
    return arr; // return the arranged array
}
 
// Example 1
let arr1 = [3, 6, 12, 1, 5, 8];
let arrangedArr1 = arrangeArray(arr1);
console.log(arrangedArr1.join(" "));
 
// Example 2
let arr2 = [10, 9, 7, 18, 13, 19, 4, 20, 21, 14];
let arrangedArr2 = arrangeArray(arr2);
console.log(arrangedArr2.join(" "));


C#




using System;
using System.Collections.Generic;
 
class Program
{
    static List<int> arrangeArray(List<int> arr)
    {
        int i = 0;
        int j = 1;
        int n = arr.Count;
        while (i < n && j < n)
        {
            if (arr[i] % 2 != 0 && arr[j] % 2 == 0)
            {
                int temp = arr[i];
                arr[i] = arr[j];
                arr[j] = temp;
                i += 2;
                j += 2;
            }
            else
            {
                if (arr[i] % 2 == 0)
                {
                    i += 2;
                }
                if (arr[j] % 2 != 0)
                {
                    j += 2;
                }
            }
        }
        return arr;
    }
 
    static void Main(string[] args)
    {
        // Example 1
        List<int> arr1 = new List<int> { 3, 6, 12, 1, 5, 8 };
        List<int> arranged_arr1 = arrangeArray(arr1);
        foreach (int i in arranged_arr1)
        {
            Console.Write(i + " ");
        }
        Console.WriteLine();
 
        // Example 2
        List<int> arr2 = new List<int> { 10, 9, 7, 18, 13, 19, 4, 20, 21, 14 };
        List<int> arranged_arr2 = arrangeArray(arr2);
        foreach (int i in arranged_arr2)
        {
            Console.Write(i + " ");
        }
        Console.WriteLine();
 
        Console.ReadLine();
    }
}


Output

[6, 3, 12, 1, 8, 5]
[10, 9, 18, 7, 20, 19, 4, 13, 14, 21]

This algorithm runs in O(n) time complexity and O(1) space complexity

 



Similar Reads

Count numbers from given range having odd digits at odd places and even digits at even places
Given two integers L and R, the task is to count numbers from the range [L, R] having odd digits at odd positions and even digits at even positions respectively. Examples: Input: L = 3, R = 25Output: 9Explanation: The numbers satisfying the conditions are 3, 5, 7, 9, 10, 12, 14, 16 and 18. Input: L = 128, R = 162Output: 7Explanation: The numbers sa
15+ min read
Count of numbers of length N having prime numbers at odd indices and odd numbers at even indices
Given a number N, the task is to calculate the count of numbers of length N having prime numbers at odd indices and odd numbers at even indices. Example: Input : N = 1Output: 5Explanation : All valid numbers length 1 are 1, 3, 5, 7, 9, here we have only 1 odd index, therefore we have 5 valid numbers. Input: N = 2Output: 20 Explanation: There are 20
5 min read
Find the nearest odd and even perfect squares of odd and even array elements respectively
Given an array arr[ ] of size N, the task for each array element is to print the nearest perfect square having same parity. Examples: Input: arr[ ] = {6, 3, 2, 15}Output: 4 1 4 9Explanation:The nearest even perfect square of arr[0] (= 6) is 4.The nearest odd perfect square of arr[1] (= 3) is 1.The nearest even perfect square of arr[2] (= 2) is 4The
5 min read
Count of integers in a range which have even number of odd digits and odd number of even digits
Given a range [L, R], the task is to count the numbers which have even number of odd digits and odd number of even digits. For example, 8 has 1 even digit and 0 odd digit - Satisfies the condition since 1 is odd and 0 is even.545 has 1 even digit and 2 odd digits - Satisfies the condition since 1 is odd and 2 is even.4834 has 3 even digits and 1 od
11 min read
Check if a number has an odd count of odd divisors and even count of even divisors
Given an integer N, the task is to check if N has an odd number of odd divisors and even number of even divisors. Examples: Input: N = 36Output: YesExplanation:Divisors of 36 = 1, 2, 3, 4, 6, 9, 12, 18, 36Count of Odd Divisors(1, 3, 9) = 3 [Odd]Count of Even Divisors(2, 4, 6, 12, 18, 36) = 6 [Even] Input: N = 28Output: No Naive Approach: The idea i
9 min read
Modify Binary Tree by replacing all nodes at even and odd levels by their nearest even or odd perfect squares respectively
Given a Binary Tree consisting of N nodes, the task is to replace all the nodes that are present at even-numbered levels in a Binary Tree with their nearest even perfect square and replace nodes at odd-numbered levels with their nearest odd perfect square. Examples: Input: 5 / \ 3 2 / \ 16 19 Output: 9 / \ 4 4 / \ 9 25 Explanation: Level 1: Nearest
13 min read
Number of permutations such that sum of elements at odd index and even index are equal
Given N numbers, find the number of permutations in which the sum of elements at odd index and sum of elements at even index are equal. Examples: Input: 1 2 3 Output: 2 The permutations are: 1 3 2 sum at odd index = 1+2 = 3, sum at even index = 3 2 3 1 sum at odd index = 2+1 = 3, sum at even index = 3 Input: 1 2 1 2 Output: 3 The permutations are:
8 min read
Rearrange array such that even index elements are smaller and odd index elements are greater
Given an array, rearrange the array such that : If index i is even, arr[i] &lt;= arr[i+1]If index i is odd, arr[i] &gt;= arr[i+1] Note: There can be multiple answers. Examples: Input : arr[] = {2, 3, 4, 5} Output : arr[] = {2, 4, 3, 5} Explanation : Elements at even indexes are smaller and elements at odd indexes are greater than their next element
11 min read
Absolute difference between sum of even elements at even indices & odd elements at odd indices in given Array
Given an array arr[] containing N elements, the task is to find the absolute difference between the sum of even elements at even indices &amp; the count of odd elements at odd indices. Consider 1-based indexing Examples: Input: arr[] = {3, 4, 1, 5}Output: 0Explanation: Sum of even elements at even indices: 4 {4}Sum of odd elements at odd indices: 4
5 min read
Count N-digits numbers made up of even and prime digits at odd and even positions respectively
Given a positive integer N, the task is to find the number of integers of N digits having even digits at odd indices and prime digits at even indices. Examples: Input: N = 2Output: 20Explanation:Following are the possible number of 2-digits satisfying the given criteria {20, 22, 24, 26, 28, 30, 32, 34, 36, 38, 50, 52, 54, 56, 58, 70, 72, 74, 76, 78
12 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg