分离的阵列,用于偶数和奇数奇数、偶数、阵列

2023-09-11 23:18:01 作者:绝版丑男丶

我已经实现一种算法以改变阵列,使所有的偶数被移动到阵列和旧号码到阵列的端部的开始。这是我的计划: -

I have implemented an algorithm to change an array so that all the even numbers are moved to the beginning of the array and the old numbers to the end of the array. Here is my program :-

#include <iostream>
using namespace std;

void print(int arr[], int size) {
    for(int i=0;i<size;i++) {
        cout<<arr[i]<<" ";
    }
    cout<<endl;
}

void segregate(int arr[], int size) {
    int l=0, h=size-1;

    while(l<h) {

        while(!(arr[l]%2) && l<size) {
            l++;
        }
        while((arr[h]%2) && h >=0) {
            h--;
        }
        swap(arr[l], arr[h]);
    }
}

int main() {

    int arr[] = {1,2,3,4,5,6,7,8,9};
    int size = 9;

    print(arr,size);

    segregate(arr,size);

    print(arr,size);

    return 0;
}

我没有得到期望的结果。

I don't get the expected result

1 2 3 4 5 6 7 8 9 
8 2 6 5 4 3 7 1 9 

我在想什么?

What am I missing?

推荐答案

你正在试图做的也被称为分区什么。标准库提供了两种算法来做到这一点:的std ::分区的std :: stable_partition

What you're trying to do is also called partitioning. The standard library provides two algorithms to do just that: std::partition and std::stable_partition.

int main()
{
   int arr[] = {1,2,3,4,5,6,7,8,9};

   auto split = std::partition( std::begin(arr), std::end( arr ),
         []( int a ) { return ! a%2; } );

   // [ begin, split ) are all even
   // [ split, end ) are all odd
}

http://ideone.com/kZI5Zh

如果你还在有趣的编写自己的,的 CP preference 的描述::分区包括相当于code。 你的版本是缺少如果语句交换之前。您应该只交换时,有左边一个奇怪的。

If you're still interesting in writing your own, cppreference's description of std::partition includes the equivalent code. Your version is missing an if statement right before the swap. You should only swap when there is an odd on the left.