You have an array of numbers.
Your task is to sort ascending odd numbers but even numbers must be on their places.Zero isn’t an odd number and you don’t need to move it. If you have an empty array, you need to return it.ExamplesortArray([5, 3, 2, 8, 1, 4]) == [1, 3, 2, 8, 5, 4]
思路
题目要求如果是偶数就不动,其他的奇数进行排序。
那其实就很简单了,我用选择排序完成这个任务,加一个偶数判定即可。
另外最开始判断一下vector是否为empty,代码如下
C++代码实现
#include <iostream>
#include <vector>
using namespace std;
class Kata
{
public:
std::vector<int> sortArray(std::vector<int> array)
{
if (array.empty())
return array;
for (auto i = array.begin(); i != array.end() - 1; ++i)
{
for (auto j = i + 1; j != array.end(); ++j)
{
if (*i % 2 == 0)
break;
if (*j % 2 == 0)
continue;
else
{
if (*i > *j)
{
int temp = *j;
*j = *i;
*i = temp;
}
}
}
}
return array;
}
};
int main()
{
Kata kata;
vector<int> T;
T = kata.sortArray({5, 3, 2, 8, 1, 4});
for (auto i = T.begin(); i != T.end(); ++i)
cout << *i;
return 0;
}
总结
看到自己C++水平的进步,我着实欣慰。还能说什么呢?别怂就是干!