2017-09-17 150 views
0

我想分离数组中的奇数和偶数。但是,它似乎并不奏效。这是我迄今为止编写函数的方法。它只适用于我输入偶数的输入。例如,如果我输入{1,2,3,4,5,6}作为输入,那么它会给出{1,5,3,6,2,4}作为输出,但是如果我给出奇数个输入,那么它会给了我一些随机的输出。代码有什么问题?如何分离数组中的奇数和偶数?

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; 
} 
} 
+0

'<= endofarray'肯定是不错的。另外假设外环指数告诉你你遇到了多少个奇数。 –

+0

你看过右边的“相关”列表吗?它看起来像[这个问题](https:// stackoverflow。com/questions/8514924 /为偶数和奇数分开数组?rq = 1)提出了类似的问题。 – user1118321

+2

[分离奇数和偶数号码的数组(https://stackoverflow.com/questions/8514924/segregating-an-array-for-even-and-odd-numbers) – akshayk07

回答

2

其实是有一个标准的算法是:

#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"; 
} 

这将让你一个正确排序:

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

如果相对顺序并不重要,使用std::partition()
如果您希望将零视为均匀,请调整条件。
务必小心妥善处理条件。

0

你的方式效率很低。 我建议你做以下操作: 1)创建两个列表(std :: list):一个用于奇数,一个用于偶数 2)遍历数组并填充odd_nums和even_nums列表 3) odd_nums列表,然后通过even_nums列表,并覆盖原始数组的内容。 这需要O(n)内存,但速度非常快。

0

这是一种使用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; 
} 

它将排序在所述第二半的载体中,从而偶数是在第一半,和奇数。当印有:

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

输出是:

0 2 4 6 8 10 1 3 5 7 9 

如果你想单号是第一位的,你可以简单地交换谓词(b & 1) && !(a & 1)ab的位置。谓词基本上检查b是否为奇数,而a不是,并将其结果传递给std::sort算法,该算法将在此后对元素进行排序。

如果你事后想偶数和奇数分成不同的容器中,可以使用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()); 

哪样产生一个偶数的矢量,一个奇数的矢量。