// 奇数在前,偶数在后,
#include <iostream>
#include <assert.h>
#include <algorithm>
using namespace std;
void swapIntArr(int *an, int n)
{
assert(NULL !=an);
int *p1=an, *p2=an+n-1;
while (p1 < p2)
{
while (*p1 %2 !=0)
{
p1++;
}
while (*p2 %2 == 0)
{
p2--;
}
int t=*p1;
*p1=*p2;
*p2=t;
p1++;
p2--;
}
}
int main()
{
int an[]={3,5,2,5,2,6,8,3,25,65,67,78,34,2,32,3};
int n=sizeof(an)/sizeof(int);
copy(an,an+n,ostream_iterator<int>(cout, " "));
cout<<endl;
swapIntArr(an,n);
copy(an,an+n,ostream_iterator<int>(cout, " "));
cout<<endl;
return 0;
}
整数数组,奇数在前,偶数在后。

本文介绍了一个简单的算法,用于将整数数组中的奇数和偶数进行分离,确保所有奇数位于数组的前面,而所有偶数位于后面。通过使用两个指针从数组两端向中间移动的方式,该算法有效地实现了奇偶数的重新排列。
598

被折叠的 条评论
为什么被折叠?



