Segregate Even and Odd numbers - GeeksforGeeks
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.
Read full article from Segregate Even and Odd numbers - GeeksforGeeks
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.
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]
oid
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--;
}
}
}