簡體   English   中英

如何分隔數組中的奇數和偶數?

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

我試圖將奇數和偶數隔離在一個數組中。 但是,它似乎不起作用。 到目前為止,這是我編寫函數的方法。 僅當我輸入偶數個輸入時,它才起作用。 例如,如果我輸入{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)遍歷數組並填充奇數和偶數列表3)遍歷奇數列表,然后然后在even_nums列表上,並覆蓋原始數組的內容。 這需要O(n)內存,但速度非常快。

這是使用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());

它將產生一個帶有偶數的向量,以及一個帶有奇數的向量。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM