我如何在数组中隔离奇数甚至数字

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

本文关键字:数字 隔离 数组      更新时间:2023-10-16

我试图将数组中的奇数隔离,甚至数字。但是,它似乎不起作用。这是我到目前为止编写该功能的方法。它只有在我放入偶数输入的情况下才起作用。例如,如果我输入{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;
}
}

实际上有一个标准算法:

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

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

这是您可以使用std::vector和库算法进行操作的方法,因为在C 中,通常最好使用库库容器,例如std::vector'S,而不是原始数组,因为它们通常是更安全,与标准库的设计更兼容,并且具有有效增长的动态大小:

#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不是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());

将产生一个具有均匀数的向量,一个奇数。