版权声明:一辈子做程序员有何不可? https://blog.csdn.net/yoyo18520/article/details/8682923
开始写写博客,做做笔记,学习学习。
//给定一个存放整数的数组,重新排列数组使得数组左边为奇数,右边为偶数。
#include <iostream>
using namespace std;
void dis(int iNum[], int l)
{
int i = 0;
while(i != l) cout << iNum[i++] << " ";
cout << endl;
}
void swap_num(int & a, int & b)
{
int temp = a;
a = b;
b = temp;
}
int main()
{
int iNum[] = {3, 34,32, 21, 11, 53, 6, 17, 4, 8, 64, 71, 37, 87};
//iNum的长度
int sz = sizeof(iNum) / sizeof(iNum[0]);
dis(iNum, sz);
int *head = iNum;
int *last = &iNum[sz - 1];
while(head < last)
{
//左边开始,是奇数时往后挪
while(((*head) % 2 == 1) && head < last) ++head;
//右边开始,是偶数时往前挪
while(((*last) % 2 == 0) && head < last) --last;
//交换指针内的数字
swap_num(*head, *last);
}
dis(iNum, sz);
system("pause");
return 0;
}
运行结果如下: