您的位置:首页 > 其它

给定一个存放整数的数组,重新排列数组使得数组左边为奇数,右边为偶数

2013-03-04 22:46 501 查看


给定一个存放整数的数组,重新排列数组使得数组左边为奇数,右边为偶数

分类: c/c++ 数据结构+算法2011-07-16
22:40 594人阅读 评论(0) 收藏 举报

[cpp] view
plaincopyprint?

/*

给定一个存放整数的数组,重新排列数组使得数组左边为奇数,右边为偶数。

要求:空间复杂度O(1),时间复杂度为O(n)。

//*/

#include <iostream>

#include <iomanip>

#include <limits>

using namespace std;

void swap_int(int& a, int& b)

{

int t = a;

a = b;

b = t;

}

int main()

{

int numel[] = {1, 23, 2, 34, 21, 45, 26, 22, 41, 66, 74, 91, 17, 64};

int sz = sizeof(numel)/sizeof(numel[0]);

for(int i =0; i<sz; ++i){

cout << numel[i] << " ";

}

cout << endl;

int begin = 0;

int end = sz -1;

while(begin < end){

while(numel[begin]%2 == 1 && end > begin){

++begin;

}

while(numel[end]%2 == 0 && end > begin){

--end;

}

swap_int(numel[begin], numel[end]);

}

for(int i =0; i<sz; ++i){

cout << numel[i] << " ";

}

cout << endl;

return 0;

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