![]() |
VOOZH | about |
Given an array arr[] of integers, segregate even and odd numbers in the array such that all the even numbers should be present first, and then the odd numbers.
Examples:
Input: arr[] = {7, 2, 9, 4, 6, 1, 3, 8, 5}
Output: 2 4 6 8 7 9 1 3 5Input: arr[] = {1, 3, 2, 4, 7, 6, 9, 10}
Output: 2 4 6 10 7 1 9 3
We have discussed two different approaches in Segregate Even and Odd numbers
Here we are going to discuss Lomuto’s Partition Scheme to segregate even and odd.
For the sake of illustration, let's consider the following array: [7, 2, 9, 4, 6, 1, 3, 8, 5].
In this case, let's choose the last element, which is 5, as the pivot.
Updated Array: 2 4 6 8 5 1 3 7 9
Illustration
Let's go through the steps:
- Initially, i = 0 and j = 0.
- The first element is 7 (odd),
- so we do nothing and move j to the next element.
- The second element is 2 (even),
- so we swap it with the element at index i (which is also 2) and increment i to 1.
- The third element is 9 (odd),
- so we do nothing and move j to the next element.
- The fourth element is 4 (even),
- so we swap it with the element at index i (which is 9) and increment i to 2.
- The fifth element is 6 (even),
- so we swap it with the element at index i (which is 9) and increment i to 3.
- The sixth element is 1 (odd),
- so we do nothing and move j to the next element.
- The seventh element is 3 (odd),
- so we do nothing and move j to the next element.
- The eighth element is 8 (even),
- so we swap it with the element at index i (which is 1) and increment i to 4.
- The ninth element is 5 (odd),
- so we do nothing and move j to the next element.
The array now looks like this: [2, 4, 6, 8, 5, 1, 3, 9, 7].
In this case, we swap 5 with 7. This step ensures that the pivot element is in its final sorted position.
The array after the final swap will be: [2, 4, 6, 8, 7, 1, 3, 9, 5].
Time Complexity: O(n)
Auxiliary Space: O(1), since no extra space has been taken.