【问题标题】:How do I segregate odd and even numbers in an array?如何分隔数组中的奇数和偶数?
【发布时间】:2017-09-17 05:06:18
【问题描述】:

我试图在一个数组中分离奇数和偶数。但是,它似乎不起作用。到目前为止,这是我编写函数的方法。只有当我输入偶数个输入时它才有效。例如,如果我输入 {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;
}
}

【问题讨论】:

  • &lt;= endofarray 肯定不好。此外,假设外部循环索引告诉您遇到了多少奇数。
  • 您查看过右侧的“相关”列表吗?看起来this question 也在问类似的问题。
  • 如何在数组的一侧放置满足特定条件的数字"?除了使用std::partitionstable_partition 之外的任何答案都是针对限制性的学校作业。甚至这些功能的名称都说明了它们的作用,而它们的作用正是您要解决的问题。

标签: c++ arrays


【解决方案1】:

实际上有一个标准算法:

#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()
如果您希望将零视为偶数,请调整条件。
始终小心正确处理条件。

【讨论】:

    【解决方案2】:

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

    【讨论】:

      【解决方案3】:

      这是一种您可以使用 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 &amp; 1) &amp;&amp; !(a &amp; 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());
      

      这将产生一个带有偶数的向量和一个带有奇数的向量。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-01-20
        相关资源
        最近更新 更多