C++ program to separate even and odd numbers from an array

C++ program to separate even and odd numbers from an array of integers. Put all even numbers first, and then odd numbers.

Given: An array having even and odd integers. We have to segregate even and odd integers and put even numbers first and then odd numbers. 

Example:

Input: {2, 5, 1, 10, 3, 6, 7, 8}

Output: 2 8 6 10 3 1 7 5

# Algorithm

  1. Initialize two index variables left and right at the beginning and end of the array, respectively.
  2. Increment the left index until an odd number is encountered.
  3. Decrement the right index until an even number is encountered.
  4. If left is less than right, swap the elements at the indices left and right.
  5. Repeat the above steps until left is greater than or equal to right.
  6. After the loop finishes, the array will be divided into two parts: even numbers at the beginning and odd numbers at the end.

Code:

#include<iostream>
using namespace std;

void swap(int *x, int *y)
{
  int t = *x;
  *x = *y;
  *y = t;
}

void segregate(int array[], int n)
{
  int left = 0, right = n - 1;
  while (left < right)
  {
    while (array[left] % 2 == 0 && left < right)
      left++;
    while (array[right] % 2 == 1 && left < right)
      right--;
    if (left < right)
    {
      swap(&array[left], &array[right]);
      left++;
      right--;
    }
  }
}

int main()
{
  int array[100], n, i;
  cout << "Enter number of elements: ";
  cin >> n;
  cout << "\nEnter elements: ";

  for (i = 0; i < n; i++)
    cin >> array[i];

  cout << "Original array: ";
  for (int i = 0; i < n; i++)
    cout << array[i] << " ";

  segregate(array, n);
  cout << "\nArray after divided: ";

  for (int i = 0; i < n; i++)
    cout << array[i] << " ";

  return 0;
}

Output

Enter number of elements: 5

Enter elements: 1 2 3 4 5
Original array: 1 2 3 4 5
Array after divided: 2 4 1 3 5