How to separate even and odd numbers in an array in C++

Separating even and odd numbers in an array is a common task in programming. In this Answer, we will discuss how to separate odd and even numbers in a one-dimensional array.

Example of what the algorithm does
Example of what the algorithm does

Code

Let's implement the logic for separating the odd and even numbers in a one-dimensional array.

#include <iostream>
using namespace std;
int main() {
// declare the array
const int size = 10;
int values[size] = {2, 3, 4, 6, 8, 5, 1, 10, 7, 9};
// temporary variable to aid in swapping
int temp;
// for loop to iterate through the array
for(int i = 0; i < size; i++)
{
// if current element is even, do nothing
if(values[i] % 2 == 0)
{
continue;
}
// else if current element is odd,
// run another for loop to check
// every subsequent element in the array
for(int j = i + 1; j < size; j++)
{
// if the subsequent element is even
if(values[j] % 2 == 0)
{
// swap the current element and this subsequent element
temp = values[i];
values[i] = values[j];
values[j] = temp;
}
}
}
// for loop to print array
for(int i = 0; i < size; i++)
{
cout << values[i] << " ";
}
return 0;
}

Explanation

  1. First, declare your int array.
  2. Run a for loop from i = 0 to i = size to iterate through the array.
  3. If the element is an even number, skip it.
  4. If the element is an odd number, run another for loop inside the first loop. This nested for loop must run from the subsequent element to the end of the array (from j = i + 1 to j = size). This for loop will check every subsequent element in the array to determine where the current element needs to be moved.
  5. If the subsequent element is an even number, swap it with the current element. If the subsequent element is an odd number, nothing is required.
  6. The for loop will run to the end of the array and keep swapping until the even and odd numbers are separated.

Test yourself

Challenge yourself by updating a given code snippet to rearrange an array in such a way that odd numbers are displayed first, followed by even numbers:

#include <iostream>
void segregate(int values[], int size) {
int temp;
// for loop to iterate through the array
for (int i = 0; i < size; i++) {
if (values[i] % 2 == 0) {
continue;
}
for (int j = i + 1; j < size; j++) {
if (values[j] % 2 == 0) {
temp = values[i];
values[i] = values[j];
values[j] = temp;
}
}
}
}

Free Resources