7.调整数组顺序使奇数位于偶数前面
题目内容:
代码及思路:
1.用最基础的遍历的方式,即遍历数组若是奇数则取出,偶数后之。
#include<iostream>
#include<vector>
using namespace std;
class solution
{
public:
void reorderarray(vector<int>& ori_array)
{
//保证奇数在前偶数在后,采用遍历的方式
vector<int> res;
for (int i = 0; i < ori_array.size(); i++)
{
if (ori_array[i] % 2 == 1)
res.push_back(ori_array[i]);
}
for (int i = 0; i < ori_array.size(); i++)
{
if (ori_array[i] % 2 == 0)
res.push_back(ori_array[i]);
}
ori_array = res;
}
};
void main()
{
vector<int> ori_array;
int num;
char ch;
do
{
cin >> num;
ori_array.push_back(num);
cin.get(ch);
} while (ch == ',');
solution* object = new solution();
object->reorderarray(ori_array);
for (int i = 0; i < ori_array.size(); i++)
{
cout << ori_array[i] << endl;
}
}
2.使用指针进行比较,只需要遍历1次,但是该种方法会改变原始奇数与奇数,偶数与偶数的相对位置。
#include<iostream>
#include<vector>
using namespace std;
class solution
{
public:
void reorderarray(int* data,int length)
{
int p1 = 0;
int p2 = length-1;
//p1向后寻找直到指向偶数,p2向前直到指向奇数,使得对换后奇数在前偶数在后
while (p1 != p2)
{
while (p1!=p2&&data[p1]%2!=0)
p1++;
while (p1 != p2&&data[p2] % 2 == 0)
p2--;
if (p1 < p2) //此时p1指向偶数,p2指向奇数
{
int temp = data[p1];
data[p1] = data[p2];
data[p2] = temp;
}
}
}
};
void main()
{
vector<int> ori_array;
int num;
char ch;
do
{
cin >> num;
ori_array.push_back(num);
cin.get(ch);
} while (ch == ',');
solution* object = new solution();
int* data = &ori_array[0];
int length = ori_array.size();
object->reorderarray(data,length);
for (int i = 0; i < ori_array.size(); i++)
{
cout << ori_array[i] << endl;
}
}