左边为奇数,右边为偶数

#include<iostream>
#include<algorithm>
#include<numeric>
using namespace std;

void helper(int a[],const int n)
{
    int left = 0;
    int right = n-1;
    while(left<right)
    {
      while(a[left]%2 == 0 && left<right)
       left++;
      
      while(a[right]%2 != 0 && right>left)
       right--;

      swap(a[left],a[right]);
    }
}

int main()
{
    int a[] = {1,2,3,4,5,6,7,8};
    helper(a,8);
    for(int i = 0;i< 8;i++)
    {
     cout<<a[i]<<" ";
    }
}

注意: 中间的两个while带有不能跑到另一半的判定,注意跳出的时候,其实他们自己跟自己也换了一下,思考一下

berkeleysong
原文地址:https://www.cnblogs.com/berkeleysong/p/3735758.html