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.
This is an variation of famous Dutch national flag problem.
Read full article from Segregate Even and Odd numbers | GeeksforGeeks
This is an variation of famous Dutch national flag problem.
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]
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--;
}
}
}