Segregate Even and Odd Numbers

What do you understand by the title `Segregate even and odd numbers` ? Let’s decode.

The goal of this problem is to separate the even and odd numbers in the input array while preserving the order of the elements, which means that the even numbers should remain in the same relative order as they were in the input, and the odd numbers should remain in the same relative order as they were in the input.

Suppose we have [3, 5, 2, 6, 8, 9, 10, 11] as input, then the output will be [2, 6, 8, 10, 3, 5, 9, 11]


Let’s take a look at the approach we will follow to implement the code.

  • First, we create two different arrays, one to store the even numbers of the input array and the other to store the odd numbers of the input array.

  • After that, we traverse the input array from the first element.

  • If the element stored in the input array is even, we push it to even_array, else to odd_array.

  • After that, we clean the input array, and then first push the elements of even_array to the input array, and then push the elements of odd_array to the input array.

  • Having rearranged the elements as per the need, we can print the input array elements to the console.

Code Implementation

Here is the C++ program to Segregate even and odd numbers


#include <iostream>
#include <vector>

using namespace std;

void segregate_even_odd(vector<int>& arr) {
    vector<int> even;
    vector<int> odd;
    for (int num : arr) {
        if (num % 2 == 0) {
        } else {
    for (int num : even) {
    for (int num : odd) {

int main() {
    int n = 5;
    vector<int> arr = {1, 2, 3, 4, 5};
    cout << "After segregating even and odd numbers: ";
    for (int num : arr) {
        cout << num << " ";
    cout << endl;
    return 0;


After segregating even and odd numbers: 2 4 1 3 5

Time Complexity: O(n)

Space Complexity: O(n)


In this article, we have tried to explain the approach to segregate the even and odd numbers present in an array and print the new rearranged array, where the order of even and odd numbers do not change. I hope this article helps you to learn the concept in a better way.

Updated on: 23-Aug-2023


Kickstart Your Career

Get certified by completing the course

Get Started