# Segregate Even and Odd numbers

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

```Input  = {12, 34, 45, 9, 8, 90, 3}
Output = {12, 34, 8, 90, 45, 9, 3}

```

In the output, the order of numbers can be changed, i.e., in the above example, 34 can come before 12 and 3 can come before 9.

The problem is very similar to our old post Segregate 0s and 1s in an array, and both of these problems are variation of famous Dutch national flag problem.

```
Algorithm: segregateEvenOdd()
1) Initialize two index variables left and right:
left = 0,  right = size -1
2) Keep incrementing left index until we see an odd number.
3) Keep decrementing right index until we see an even number.
4) If lef < right then swap arr[left] and arr[right]

```

Implementation:

## C++

 `// C++ program to segregate even and odd elements of array` `#include ` `using` `namespace` `std;`   `/* Function to swap *a and *b */` `void` `swap(``int` `*a, ``int` `*b);`   `void` `segregateEvenOdd(``int` `arr[], ``int` `size)` `{` `    ``/* Initialize left and right indexes */` `    ``int` `left = 0, right = size-1;` `    ``while` `(left < right)` `    ``{` `        ``/* Increment left index while we see 0 at left */` `        ``while` `(arr[left] % 2 == 0 && left < right)` `            ``left++;`   `        ``/* Decrement right index while we see 1 at right */` `        ``while` `(arr[right] % 2 == 1 && left < right)` `            ``right--;`   `        ``if` `(left < right)` `        ``{` `            ``/* Swap arr[left] and arr[right]*/` `            ``swap(&arr[left], &arr[right]);` `            ``left++;` `            ``right--;` `        ``}` `    ``}` `}`   `/* UTILITY FUNCTIONS */` `void` `swap(``int` `*a, ``int` `*b)` `{` `    ``int` `temp = *a;` `    ``*a = *b;` `    ``*b = temp;` `}`   `/* Driver code */` `int` `main()` `{` `    ``int` `arr[] = {12, 34, 45, 9, 8, 90, 3};` `    ``int` `arr_size = ``sizeof``(arr)/``sizeof``(arr);` `    ``int` `i = 0;`   `    ``segregateEvenOdd(arr, arr_size);`   `    ``cout <<``"Array after segregation "``;` `    ``for` `(i = 0; i < arr_size; i++)` `        ``cout << arr[i] << ``" "``;`   `    ``return` `0;` `}`   `// This code is contributed by shubhamsingh10`

## C

 `// C program to segregate even and odd elements of array` `#include`   `/* Function to swap *a and *b */` `void` `swap(``int` `*a, ``int` `*b);`   `void` `segregateEvenOdd(``int` `arr[], ``int` `size)` `{` `    ``/* Initialize left and right indexes */` `    ``int` `left = 0, right = size-1;` `    ``while` `(left < right)` `    ``{` `        ``/* Increment left index while we see 0 at left */` `        ``while` `(arr[left]%2 == 0 && left < right)` `            ``left++;`   `        ``/* Decrement right index while we see 1 at right */` `        ``while` `(arr[right]%2 == 1 && left < right)` `            ``right--;`   `        ``if` `(left < right)` `        ``{` `            ``/* Swap arr[left] and arr[right]*/` `            ``swap(&arr[left], &arr[right]);` `            ``left++;` `            ``right--;` `        ``}` `    ``}` `}`   `/* UTILITY FUNCTIONS */` `void` `swap(``int` `*a, ``int` `*b)` `{` `    ``int` `temp = *a;` `    ``*a = *b;` `    ``*b = temp;` `}`   `/* driver program to test */` `int` `main()` `{` `    ``int` `arr[] = {12, 34, 45, 9, 8, 90, 3};` `    ``int` `arr_size = ``sizeof``(arr)/``sizeof``(arr);` `    ``int` `i = 0;`   `    ``segregateEvenOdd(arr, arr_size);`   `    ``printf``(``"Array after segregation "``);` `    ``for` `(i = 0; i < arr_size; i++)` `        ``printf``(``"%d "``, arr[i]);`   `    ``return` `0;` `}`

## Java

 `// Java program to segregate even and odd elements of array` `import` `java.io.*;`   `class` `SegregateOddEven` `{` `    ``static` `void` `segregateEvenOdd(``int` `arr[])` `    ``{` `        ``/* Initialize left and right indexes */` `        ``int` `left = ``0``, right = arr.length - ``1``;` `        ``while` `(left < right)` `        ``{` `            ``/* Increment left index while we see 0 at left */` `            ``while` `(arr[left]%``2` `== ``0` `&& left < right)` `                ``left++;`   `            ``/* Decrement right index while we see 1 at right */` `            ``while` `(arr[right]%``2` `== ``1` `&& left < right)` `                ``right--;`   `            ``if` `(left < right)` `            ``{` `                ``/* Swap arr[left] and arr[right]*/` `                ``int` `temp = arr[left];` `                ``arr[left] = arr[right];` `                ``arr[right] = temp;` `                ``left++;` `                ``right--;` `            ``}` `        ``}` `    ``}`   `    ``/* Driver program to test above functions */` `    ``public` `static` `void` `main (String[] args)` `    ``{` `        ``int` `arr[] = {``12``, ``34``, ``45``, ``9``, ``8``, ``90``, ``3``};`   `        ``segregateEvenOdd(arr);`   `        ``System.out.print(``"Array after segregation "``);` `        ``for` `(``int` `i = ``0``; i < arr.length; i++)` `            ``System.out.print(arr[i]+``" "``);` `    ``}` `}` `/*This code is contributed by Devesh Agrawal*/`

## Python

 `# Python program to segregate even and odd elements of array`   `def` `segregateEvenOdd(arr):`   `    ``# Initialize left and right indexes` `    ``left,right ``=` `0``,``len``(arr)``-``1`   `    ``while` `left < right:`   `        ``# Increment left index while we see 0 at left` `        ``while` `(arr[left]``%``2``=``=``0` `and` `left < right):` `            ``left ``+``=` `1`   `        ``# Decrement right index while we see 1 at right` `        ``while` `(arr[right]``%``2` `=``=` `1` `and` `left < right):` `            ``right ``-``=` `1`   `        ``if` `(left < right):` `              ``# Swap arr[left] and arr[right]*/` `              ``arr[left],arr[right] ``=` `arr[right],arr[left]` `              ``left ``+``=` `1` `              ``right ``=` `right``-``1`     `# Driver function to test above function` `arr ``=` `[``12``, ``34``, ``45``, ``9``, ``8``, ``90``, ``3``]` `segregateEvenOdd(arr)` `print` `(``"Array after segregation "``),` `for` `i ``in` `range``(``0``,``len``(arr)):` `    ``print` `arr[i],` `# This code is contributed by Devesh Agrawal`

## C#

 `// C# program to segregate even` `// and odd elements of array` `using` `System;`   `class` `GFG` `{` `    ``static` `void` `segregateEvenOdd(``int` `[]arr)` `    ``{` `        ``/* Initialize left and right indexes */` `        ``int` `left = 0, right = arr.Length - 1;` `        ``while` `(left < right)` `        ``{` `            ``/* Increment left index while we see 0 at left */` `            ``while` `(arr[left]%2 == 0 && left < right)` `                ``left++;`   `            ``/* Decrement right index while we see 1 at right */` `            ``while` `(arr[right]%2 == 1 && left < right)` `                ``right--;`   `            ``if` `(left < right)` `            ``{` `                ``/* Swap arr[left] and arr[right]*/` `                ``int` `temp = arr[left];` `                ``arr[left] = arr[right];` `                ``arr[right] = temp;` `                ``left++;` `                ``right--;` `            ``}` `        ``}` `    ``}`   `    ``/* Driver program to test above functions */` `    ``public` `static` `void` `Main ()` `    ``{` `        ``int` `[]arr = {12, 34, 45, 9, 8, 90, 3};`   `        ``segregateEvenOdd(arr);`   `        ``Console.Write(``"Array after segregation "``);` `        ``for` `(``int` `i = 0; i < arr.Length; i++)` `            ``Console.Write(arr[i]+``" "``);` `    ``}` `}`   `//This code is contributed by Sam007`

## PHP

 ``

Output:

```Array after segregation 12 34 90 8 9 45 3

```

Time Complexity: O(n)
Alternate Implementation (Lomuto partition):

## C++

 `// A Lomuto partition based scheme to segregate` `// even and odd numbers.` `#include ` `using` `namespace` `std;`   `// Function to rearrange the array in given way.` `void` `rearrangeEvenAndOdd(``int` `arr[], ``int` `n)` `{` `    ``// Variables` `    ``int` `j = -1;`   `    ``// Quick sort method` `    ``for` `(``int` `i = 0; i < n; i++) {`   `        ``// If array of element` `        ``// is odd then swap` `        ``if` `(arr[i] % 2 == 0) {`   `            ``// increment j by one` `            ``j++;`   `            ``// swap the element` `            ``swap(arr[i], arr[j]);` `        ``}` `    ``}` `}`   `int` `main()` `{` `    ``int` `arr[] = { 12, 10, 9, 45, 2, 10, 10, 45 };` `    ``int` `n = ``sizeof``(arr) / ``sizeof``(arr);`   `    ``rearrangeEvenAndOdd(arr, n);`   `    ``for` `(``int` `i = 0; i < n; i++)` `        ``cout << arr[i] << ``" "``;` `}` `// This code is contributed by devagarwalmnnit`

## Java

 `// A Lomuto partition based scheme to segregate` `// even and odd numbers.` `import` `java.io.*;`   `class` `GFG ` `{` `    ``// function to rearrange the array in given way.` `    ``static` `void` `rearrangeEvenAndOdd(``int` `arr[], ``int` `n)` `    ``{` `        ``// variables` `        ``int` `j = -``1``,temp;` `    `  `        ``// quick sort method` `        ``for` `(``int` `i = ``0``; i < n; i++) {` `    `  `            ``// if array of element` `            ``// is odd then swap` `            ``if` `(arr[i] % ``2` `== ``0``) {` `    `  `                ``// increment j by one` `                ``j++;` `    `  `                ``// swap the element` `                ``temp = arr[i];` `                ``arr[i] = arr[j];` `                ``arr[j] = temp;` `            ``}` `        ``}` `    ``}` `    `  `    ``// Driver code` `    ``public` `static` `void` `main(String args[])` `    ``{` `        ``int` `arr[] = { ``12``, ``10``, ``9``, ``45``, ``2``, ``10``, ``10``, ``45` `};` `        ``int` `n = arr.length;` `    `  `        ``rearrangeEvenAndOdd(arr, n);` `    `  `        ``for` `(``int` `i = ``0``; i < n; i++)` `            ``System.out.print(arr[i] + ``" "``);` `    ``}` `}`   `// This code is contributed by Nikita Tiwari.`

## Python3

 `# A Lomuto partition based scheme to ` `# segregate even and odd numbers.`   `# function to rearrange the ` `# array in given way.` `def` `rearrangeEvenAndOdd(arr, n) :` `    ``# variables` `    ``j ``=` `-``1`   `    ``# quick sort method` `    ``for` `i ``in` `range``(``0``, n) :` `        `  `        ``# if array of element` `        ``# is odd then swap` `        ``if` `(arr[i] ``%` `2` `=``=` `0``) :` `            ``# increment j by one` `            ``j ``=` `j ``+` `1`   `            ``# swap the element` `            ``temp ``=` `arr[i]` `            ``arr[i] ``=` `arr[j]` `            ``arr[j] ``=` `temp` `        `    `# Driver code        ` `arr ``=` `[ ``12``, ``10``, ``9``, ``45``, ``2``, ``10``, ``10``, ``45` `]` `n ``=` `len``(arr)`   `rearrangeEvenAndOdd(arr, n)`   `for` `i ``in` `range``(``0``,n) :` `    ``print``( arr[i] ,end``=` `" "``)` `    `  `        `  `# This code is contributed by Nikita Tiwari.`

## C#

 `// A Lomuto partition based scheme ` `// to segregate even and odd numbers.` `using` `System;`   `class` `GFG` `{` `    ``// function to rearrange` `    ``// the array in given way.` `    ``static` `void` `rearrangeEvenAndOdd(``int` `[]arr,` `                                        ``int` `n)` `    ``{` `        ``// variables` `        ``int` `j = -1, temp;` `    `  `        ``// quick sort method` `        ``for` `(``int` `i = 0; i < n; i++) {` `    `  `            ``// if array of element` `            ``// is odd then swap` `            ``if` `(arr[i] % 2 == 0) {` `    `  `                ``// increment j by one` `                ``j++;` `    `  `                ``// swap the element` `                ``temp = arr[i];` `                ``arr[i] = arr[j];` `                ``arr[j] = temp;` `            ``}` `        ``}` `    ``}` `    `  `    ``// Driver code` `    ``public` `static` `void` `Main()` `    ``{` `        ``int` `[]arr = { 12, 10, 9, 45, 2, ` `                            ``10, 10, 45 };` `        ``int` `n = arr.Length;` `    `  `        ``rearrangeEvenAndOdd(arr, n);` `    `  `        ``for` `(``int` `i = 0; i < n; i++)` `            ``Console.Write(arr[i] + ``" "``);` `    ``}` `}`   `// This code is contributed by Sam007`

## PHP

 `

Output:

```12 10 2 10 10 45 9 45

```

Time Complexity: O(n)
References:
http://www.csse.monash.edu.au/~lloyd/tildeAlgDS/Sort/Flag/
Please write comments if you find the above code/algorithm incorrect, or find better ways to solve the same problem.

Alternate Implementation (Using stable partition):

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. The partitioning is stable. This means that the relative ordering of the sequence is preserved.

Syntax:

```template
BiIter stable_partition(BiIter start, BiIter end, UnPred pfn);
```

Parameters:

```start: the range of elements to reorder
end: the range of elements to reorder
pfn: User-defined predicate function object that defines the condition to be satisfied if an element
is to be classified. A predicate takes single argument and returns true or false.
Return Value:
Returns an iterator to the beginning of the elements for which the predicate is false.
```

This function attempts to allocate a temporary buffer. If the allocation fails, the less efficient algorithm is chosen.

Below is the implementation of the above logic.

Code:

## C++14

 `// CPP program for above approach` `#include ` `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`

Output

```18 52 70 2 34 37 3 63
```

Time Complexity:

If enough extra memory is available, linear in the distance between first and last i.e (O(N) ,where N is the distance between first and last). It applies predicate (i.e 3rd parameter of above code) exactly once to each element, and performs up to that many element moves.

Otherwise, performs up to N*log(N) element swaps (where N is the distance above). It also applies predicate exactly once to each element.

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.

My Personal Notes arrow_drop_up

Article Tags :

8

Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.