您的位置:首页 > 其它

重新排列数组,使得数组左边的数字为奇数,数组右边的数字为偶数

2015-03-16 15:17 309 查看
源程序:

#include<iostream>
using namespace std;
void Swap(int &a,int &b)
{
int temp;
temp=a;
a=b;
b=temp;
}

void Change(int *a,int n)
{
int nl=0;
int nr=n-1;
while(nl<nr)
{
while(nl<nr&&a[nl]%2==1)
nl++;
while(nl<nr&&a[nr]%2==0)
nr--;
Swap(a[nl],a[nr]);
}
}

void Show(int *a,int n)
{
for(int i=0;i<n;i++)
cout<<a[i]<<"  ";
cout<<endl;
}

int main()
{
int a[]={1,2,3,4,5,6,7,8,9};
int length_a=sizeof(a)/sizeof(a[0]);
cout<<"交换前:";
Show(a,length_a);
Change(a,length_a);
cout<<"交换后:";
Show(a,length_a);
cout<<endl;
system("pause");
return 0;
}


输出结果:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐