简体   繁体   English

如何分隔数组中的奇数和偶数?

[英]How do I segregate odd and even numbers in an array?

I am trying to segregate odd and even numbers in an array. 我试图将奇数和偶数隔离在一个数组中。 But, it does not seem to work. 但是,它似乎不起作用。 This is my approach in writing the function so far. 到目前为止,这是我编写函数的方法。 It works only if I put even number of inputs. 仅当我输入偶数个输入时,它才起作用。 Example, if I enter {1,2,3,4,5,6} as an input then it gives me {1,5,3,6,2,4} as output but if I give odd number of input then it gives me some random output. 例如,如果我输入{1,2,3,4,5,6}作为输入,那么它给了我{1,5,3,6,2,4}作为输出,但是如果我输入的是奇数,则它给我一些随机输出。 What is the problem with the code ? 代码有什么问题?

edit1 : I am a beginner in c++. edit1:我是C ++的初学者。

void segregateEvenOdd() {

for (int i = 0; i < endofarray; i++){
    int temp;
    if (array[i] % 2 == 0) //check if the number is odd or even
        temp = array[i];
        for(int j = i; j <= endofarray; j++){ //start from 1 cuz we dont want to touch the numbers that are already segregated
            array[j] = array[j+1];

        }
        array[endofarray] = temp;
}
}

There is actually a Standard Algorithm for that: 实际上有一个标准算法可以做到这一点:

#include <algorithm>
#include <ciso646>
#include <cmath>
#include <iostream>
#include <iterator>

int main()
{
  int xs[] = { -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5 };

  std::stable_partition( std::begin(xs), std::end(xs), []( int x ) 
  { 
    return x and ((std::abs(x) % 2) == 0);
  } );

  for (int x : xs) std::cout << x << " "; 
  std::cout << "\n";
}

This will get you a correctly ordered: 这将为您正确订购:

-4 -2 2 4 -5 -3 -1 0 1 3 5

If relative order does not matter, use std::partition() . 如果相对顺序无关紧要,请使用std::partition()
If you wish zero to be considered as even, adjust the condition. 如果希望零被视为偶数,请调整条件。
Always be careful to handle conditions properly. 始终要小心处理条件。

Your way is very inefficient. 您的方式效率很低。 I suggest you do the following: 1) Create two lists (std::list): one for odd numbers, and one for even numbers 2) Iterate over the array and populate the odd_nums and even_nums lists 3) Go over the odd_nums list and then over the even_nums list, and override the contents of the original array. 我建议您执行以下操作:1)创建两个列表(std :: list):一个用于奇数,一个用于偶数2)遍历数组并填充奇数和偶数列表3)遍历奇数列表,然后然后在even_nums列表上,并覆盖原始数组的内容。 This takes O(n) memory, but is very fast. 这需要O(n)内存,但速度非常快。

Here is a way you can do it using std::vector and the library algorithms, since in C++ it is normally preferable to use library containers such as std::vector 's rather than raw arrays because they are generally safer, are more compatible with the design of the standard library, and have a dynamic size which grows efficiently: 这是使用std::vector和库算法的一种方法,因为在C ++中,通常最好使用std::vector之类的库容器,而不是原始数组,因为它们通常更安全,并且更兼容具有标准库的设计,并且具有动态增长的大小,可以有效地增长:

#include <iostream>
#include <iterator>
#include <algorithm>
#include <vector>

int main() {
    std::vector<int> iVec { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
    std::sort(iVec.begin(), iVec.end(), [](int a, int b) { return (b & 1) && !(a & 1); });

    return 0;
}

It will sort the vector so that even numbers are in the first half, and odd numbers in the second half. 它将对向量进行排序,以使偶数在上半部,而奇数在下半部。 When printed with: 打印时:

std::copy(iVec.begin(), iVec.end(), std::ostream_iterator<int>(std::cout, " "));

The output is: 输出为:

0 2 4 6 8 10 1 3 5 7 9

If you want the odd numbers to come first you can simply swap the positions of a and b in the predicate (b & 1) && !(a & 1) . 如果您希望奇数首先出现,则可以简单地交换谓词(b & 1) && !(a & 1)ab的位置。 The predicate basically checks if b is odd and a is not, and the result of that is passed to the std::sort algorithm which will sort the elements thereafter. 谓词基本上检查b是否为奇数而a是否为奇数,然后将其结果传递到std::sort算法,该算法随后将对元素排序。

If you afterwards want to split the even and odd numbers into separate containers, you can use the find_if algorithm to find the first odd number, and construct two vectors from the given range: 如果以后要将偶数和奇数分开,可以使用find_if算法查找第一个奇数,并从给定范围构造两个向量:

auto it = std::find_if(iVec.begin(), iVec.end(), [](int a) { return (a & 1); });
std::vector<int> evenNumbers(iVec.begin(), it);
std::vector<int> oddNumbers(it, iVec.end());

Which will produce one vector with even numbers, and one with odd numbers. 它将产生一个带有偶数的向量,以及一个带有奇数的向量。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM