Open In App

Segregate Even and Odd numbers

Last Updated : 23 Jul, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Given an array arr[], write a function that segregates even and odd numbers. The functions should put all even numbers first, and then odd numbers.

 Example:  

Input: arr = [0, 1, 2, 3, 4]
Output: arr = [0, 2, 4, 1, 3]
Explanation: 0 2 4 are even and 1 3 are odd numbers. Please note that [2, 0, 4, 3, 1] or [4, 2, 0, 1, 3] are also valid outputs. We only need to make sure that all even elements are before all odd.

Input : arr = {1, 5, 11}
Output : arr = {1, 5, 11}
Explanation All numbers are odd

The problem is very similar to our old post Segregate 0s and 1s in an array.

Using Hoare's Partition - O(n) Time and O(1) Space

The Idea of the solution is based on Hoare's Partition Scheme of Quick Sort

1) Initialize two index variables lo and hi: lo = 0, hi = size -1
2) Keep incrementing lo index until we see an odd number.
3) Keep decrementing hi index until we see an even number.
4) If lo < hi then swap arr[lo] and arr[hi]

C++
#include <iostream>
#include <vector>
#include <algorithm> 
using namespace std;

void segregateEvenOdd(vector<int> &arr) {
    int lo = 0, hi = arr.size() - 1;

    while (lo < hi) {
      
        // Increment lo index while even number 
        // is found at lo
        while (arr[lo] % 2 == 0 && lo < hi)
            lo++;

        // Decrement hi index while odd number 
        // is found at hi
        while (arr[hi] % 2 == 1 && lo < hi)
            hi--;

        if (lo < hi) {
            swap(arr[lo], arr[hi]);
            lo++;
            hi--;
        }
    }
}

int main() {
    vector<int> arr = {12, 34, 45, 9, 8, 90, 3};
    segregateEvenOdd(arr);
    cout << "Array after segregation: ";
    for (int x : arr)
        cout << x << " ";
    return 0;
}
C
#include <stdio.h>
#include <stdlib.h>

void segregateEvenOdd(int arr[], int n) {
    int lo = 0, hi = n - 1;

    while (lo < hi) {
        while (arr[lo] % 2 == 0 && lo < hi)
            lo++;
        while (arr[hi] % 2 == 1 && lo < hi)
            hi--;
        if (lo < hi) {
            int temp = arr[lo];
            arr[lo] = arr[hi];
            arr[hi] = temp;
            lo++;
            hi--;
        }
    }
}

int main() {
    int arr[] = {12, 34, 45, 9, 8, 90, 3};
    int n = sizeof(arr) / sizeof(arr[0]);
    segregateEvenOdd(arr, n);
    printf("Array after segregation: ");
    for (int i = 0; i < n; i++)
        printf("%d ", arr[i]);
    return 0;
}
Java
import java.util.Arrays;

public class Main {
    public static void segregateEvenOdd(int[] arr) {
        int lo = 0, hi = arr.length - 1;

        while (lo < hi) {
            while (arr[lo] % 2 == 0 && lo < hi)
                lo++;
            while (arr[hi] % 2 == 1 && lo < hi)
                hi--;
            if (lo < hi) {
                int temp = arr[lo];
                arr[lo] = arr[hi];
                arr[hi] = temp;
                lo++;
                hi--;
            }
        }
    }

    public static void main(String[] args) {
        int[] arr = {12, 34, 45, 9, 8, 90, 3};
        segregateEvenOdd(arr);
        System.out.println("Array after segregation: " + Arrays.toString(arr));
    }
}
Python
def segregate_even_odd(arr):
    lo, hi = 0, len(arr) - 1
    while lo < hi:
        while lo < hi and arr[lo] % 2 == 0:
            lo += 1
        while lo < hi and arr[hi] % 2 == 1:
            hi -= 1
        if lo < hi:
            arr[lo], arr[hi] = arr[hi], arr[lo]
            lo += 1
            hi -= 1

arr = [12, 34, 45, 9, 8, 90, 3]
segregate_even_odd(arr)
print("Array after segregation:", arr)
C#
using System;
using System.Linq;

class Program {
    static void SegregateEvenOdd(int[] arr) {
        int lo = 0, hi = arr.Length - 1;
        while (lo < hi) {
            while (arr[lo] % 2 == 0 && lo < hi)
                lo++;
            while (arr[hi] % 2 == 1 && lo < hi)
                hi--;
            if (lo < hi) {
                int temp = arr[lo];
                arr[lo] = arr[hi];
                arr[hi] = temp;
                lo++;
                hi--;
            }
        }
    }

    static void Main() {
        int[] arr = {12, 34, 45, 9, 8, 90, 3};
        SegregateEvenOdd(arr);
        Console.WriteLine("Array after segregation: " + string.Join(" ", arr));
    }
}
JavaScript
function segregateEvenOdd(arr) {
    let lo = 0, hi = arr.length - 1;
    while (lo < hi) {
        while (arr[lo] % 2 === 0 && lo < hi)
            lo++;
        while (arr[hi] % 2 === 1 && lo < hi)
            hi--;
        if (lo < hi) {
            [arr[lo], arr[hi]] = [arr[hi], arr[lo]];
            lo++;
            hi--;
        }
    }
}

const arr = [12, 34, 45, 9, 8, 90, 3];
segregateEvenOdd(arr);
console.log("Array after segregation:", arr);

More Efficient Implementation of the Above Approach

  1. Using two pointers lo = 0 and hi = last index.
  2. Run a while loop; if arr[lo] is odd and arr[hi] is even then we will swap them else we will decrement hi.
C++
#include <bits/stdc++.h>
using namespace std;

// Function to segregate even and odd numbers
void segregate(vector<int>& arr) {
    int lo = 0, hi = arr.size() - 1;

    // Iterate while hi >= lo
    while (hi >= lo) {
      
        // Check if arr[lo] is odd
        if (arr[lo] % 2 != 0) {
            if (arr[hi] % 2 == 0) {
              
                // Swap arr[lo] and arr[hi]
                swap(arr[lo], arr[hi]);
                lo++;
                hi--;
            } else {
                hi--;
            }
        } else {
            lo++;
        }
    }
}

// Driver Code
int main() {
    vector<int> arr = {1, 2, 3, 4, 5, 6};
    segregate(arr);
    for (int x : arr)
        cout << x << " ";
    return 0;
}
C
#include <stdio.h>

void segregate(int arr[], int n) {
    int lo = 0, hi = n - 1;

    while (hi >= lo) {
        if (arr[lo] % 2 != 0) {
            if (arr[hi] % 2 == 0) {
              
                // Swap arr[lo] and arr[hi]
                int temp = arr[lo];
                arr[lo] = arr[hi];
                arr[hi] = temp;
              
                lo++;
                hi--;
            } else {
                hi--;
            }
        } else {
            lo++;
        }
    }
}

int main() {
    int arr[] = {1, 2, 3, 4, 5, 6};
    int n = sizeof(arr) / sizeof(arr[0]);
    segregate(arr, n);
    for (int i = 0; i < n; i++) {
        printf("%d ", arr[i]);
    }
    return 0;
}
Java
import java.util.Arrays;

public class Main {
    // Function to segregate even and odd numbers
    static void segregate(int[] arr) {
        int lo = 0, hi = arr.length - 1;

        while (hi >= lo) {
            if (arr[lo] % 2 != 0) {
                if (arr[hi] % 2 == 0) {
                  
                    // Swap arr[lo] and arr[hi]
                    int temp = arr[lo];
                    arr[lo] = arr[hi];
                    arr[hi] = temp;
                  
                    lo++;
                    hi--;
                } else {
                    hi--;
                }
            } else {
                lo++;
            }
        }
    }

    public static void main(String[] args) {
        int[] arr = {1, 2, 3, 4, 5, 6};
        segregate(arr);
        System.out.println(Arrays.toString(arr));
    }
}
Python
def segregate(arr):
    lo, hi = 0, len(arr) - 1

    while hi >= lo:
        if arr[lo] % 2 != 0:
            if arr[hi] % 2 == 0:
              
                # Swap arr[lo] and arr[hi]
                arr[lo], arr[hi] = arr[hi], arr[lo]
                
                lo += 1
                hi -= 1
            else:
                hi -= 1
        else:
            lo += 1

arr = [1, 2, 3, 4, 5, 6]
segregate(arr)
print(arr)
C#
using System;
using System.Linq;

class GfG {
  
    // Function to segregate even and odd numbers
    static void Segregate(int[] arr) {
        int lo = 0, hi = arr.Length - 1;

        while (hi >= lo) {
            if (arr[lo] % 2 != 0) {
                if (arr[hi] % 2 == 0) {
                  
                    // Swap arr[lo] and arr[hi]
                    int temp = arr[lo];
                    arr[lo] = arr[hi];
                    arr[hi] = temp;
                  
                    lo++;
                    hi--;
                } else {
                    hi--;
                }
            } else {
                lo++;
            }
        }
    }

    static void Main() {
        int[] arr = {1, 2, 3, 4, 5, 6};
        Segregate(arr);
        Console.WriteLine(string.Join(" ", arr));
    }
}
JavaScript
function segregate(arr) {
    let lo = 0, hi = arr.length - 1;

    while (hi >= lo) {
        if (arr[lo] % 2 !== 0) {
            if (arr[hi] % 2 === 0) {
            
                // Swap arr[lo] and arr[hi]
                [arr[lo], arr[hi]] = [arr[hi], arr[lo]];
                
                lo++;
                hi--;
            } else {
                hi--;
            }
        } else {
            lo++;
        }
    }
}

const arr = [1, 2, 3, 4, 5, 6];
segregate(arr);
console.log(arr);

Output
6 2 4 3 5 1 

Using Library Methods

To implement the above problem, we will use stable_partition in C++. The stable_partition() algorithm arranges the sequence defined by start and end such that all elements for which the predicate specified by pfn returns true come before those for which the predicate returns false. In languages, other than C++, we can use custom comparison function in the library sort methods to to achieve the required results. The time complexity in case of C++ might be O(n) and in case other languages O(n Log n).

C++14
// CPP program for above approach
#include <bits/stdc++.h>
using namespace std;

// Function to rearrange the array in given way.
void rearrangeEvenAndOdd(vector<int>v)
{
    
    // Using stable partition with lambda expression
    stable_partition(v.begin(), v.end(),
                     [](auto a) { return a % 2 == 0; });

    for (int num : v)
        cout << num << " ";
}

// Driver Code
int main()
{
    vector<int> v = { 12, 10, 9, 45, 2, 10, 10, 45 };
    
    // Function Call
    rearrangeEvenAndOdd(v);
    return 0;
}
// This code is contributed by Chirag Shilwant
Java
import java.io.*;
import java.util.*;

public class Main {
    // Function to rearrange the array in given way.
    public static void rearrangeEvenAndOdd(List<Integer> v) {
        // Using sort method with a custom comparator
        Collections.sort(v, new Comparator<Integer>() {
            public int compare(Integer a, Integer b) {
                return Integer.compare(a % 2, b % 2);
            }
        });

        for (int num : v)
            System.out.print(num + " ");
    }

    // Driver Code
    public static void main(String[] args) {
        List<Integer> v = new ArrayList<Integer>(Arrays.asList(12, 10, 9, 45, 2, 10, 10, 45));

        // Function Call
        rearrangeEvenAndOdd(v);
    }
}
Python
# Python equivalent

# Importing necessary modules 
import collections 

# Function to rearrange the array in given way. 
def rearrangeEvenAndOdd(v): 

    # Using sort method with a custom comparator 
    v.sort(key=lambda x: x % 2) 

    # Print the rearranged array 
    for num in v: 
        print(num, end = ' ') 

# Driver Code 
if __name__ == '__main__': 
    v = [12, 10, 9, 45, 2, 10, 10, 45] 

    # Function Call 
    rearrangeEvenAndOdd(v)
C#
using System;
using System.Collections.Generic;
using System.Linq;

public class Mainn
{
// Function to rearrange the array in given way.
public static void rearrangeEvenAndOdd(List<int> v)
{
// Using sort method with a custom comparator
v.Sort((a, b) => (a % 2).CompareTo(b % 2));
    foreach (int num in v)
        Console.Write(num + " ");
}

// Driver Code
public static void Main(string[] args)
{
    List<int> v = new List<int>(new int[] { 12, 10, 9, 45, 2, 10, 10, 45 });

    // Function Call
    rearrangeEvenAndOdd(v);
}
}
JavaScript
function rearrangeEvenAndOdd(v) {
  v.sort(function(a, b) {
    return a % 2 - b % 2;
  });

  console.log(v.join(" "));
}

// Driver Code
var v = [12, 10, 9, 45, 2, 10, 10, 45];

// Function Call
rearrangeEvenAndOdd(v);

Output
12 10 2 10 10 9 45 45 

Using Lomuto Partition - O(n) Time and O(1) Space

We can also use Lomuto Partition to achieve the results. Please refer Segregate even and odd numbers using Lomuto’s Partition for details. Please remember, Hoare's partition is always much faster than the Lomuto Partition. So the method discussed in this post would perform better.


Separate Even and Odd in Python
Visit Course explore course icon
Article Tags :
Practice Tags :

Explore