Lima
Lima

Reputation: 27

Segregate ODD and EVEN numbers in an Array using C++

I am barely new to programming, I need to sort an array of integers by having all the odd numbers on the left side and even numbers on the right side by calling a function.

This is my code.

#include <iostream>

void sortOdd(int arr[], int size) {
int odd = 0;
int even = size - 1;

while (even > odd) {
  int temp;

  while(arr[odd] % 2 != 0) {
    odd++;
  }
  while(arr[even] % 2 == 0) {
    even--;
  }

  temp = arr[odd];
  arr[odd] = arr[even];
  arr[even] = temp;
  odd++;
  even--;
}
}

int main () {

int arr[] = {1, 2, 3, 4, 5, 6};
int size = sizeof(arr) / sizeof(arr[0]);


cout << "unsorted array" << endl;
for (int i = 0; i < size; i++) cout << arr[i] << " ";

sortOdd(arr, size);

cout << "sorted array" << endl;
for (int i = 0; i < size; i++) cout << arr[i] << " ";


  return 0;
}

The problem is that it only sorts/swaps the outer elements and not the middle ones, and it outputs something like this:

unsorted array
1 2 3 4 5 6
sorted array
1 5 4 3 2 6

Can someone help what am I doing wrong here?

Thanks.

Upvotes: 2

Views: 528

Answers (2)

Acorn
Acorn

Reputation: 26066

You can use std::partition like this:

std::partition(std::begin(arr), std::end(arr), [](int a) {
    return a % 2;
});

Upvotes: 2

Phles
Phles

Reputation: 337

Change your while condition to this:

while (even > odd+1)

Your algorithm works for the most part but you took one extra iteration and it swaps your your the middle values.

Upvotes: 0

Related Questions