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]

Approach

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

Example

#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) {
            even.push_back(num);
        } else {
            odd.push_back(num);
        }
    }
    arr.clear();
    for (int num : even) {
        arr.push_back(num);
    }
    for (int num : odd) {
        arr.push_back(num);
    }
}

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

Output

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

Time Complexity: O(n)

Space Complexity: O(n)

Conclusion

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

386 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements