#ifndef PUBLIC_UTILITY
#define PUBLIC_UTILITY
#include <stdio.h>
#include <vector>
#include <algorithm>
namespace publicutility
{
using namespace std;
class PublicUtility
{
public:
/*
* @brief adjust odd elements to locate before even elements
* */
static void Odd_before_Even(vector<int>&);
/*
* @brief judge wheter a number is odd
* */
inline static bool IsOdd(int num)
{
return num & 1;
}
};
}
#endif
#include "PublicUtility.h"
namespace publicutility
{
/*
* @brief adjust odd elements to locate before even elements
* */
void PublicUtility::Odd_before_Even(vector<int>&v)
{
int nlow = 0;
int nhigh = v.size() - 1;
bool blow_is_odd = false;
bool bhigh_is_odd = false;
bool blow_is_change = true;
bool bhigh_is_change = true;
while(nlow < nhigh)
{
if(blow_is_change)
{
blow_is_odd = IsOdd(v[nlow]);
blow_is_change = false;
}
if(bhigh_is_change)
{
bhigh_is_odd = IsOdd(v[nhigh]);
bhigh_is_change = false;
}
if(!blow_is_odd && bhigh_is_odd)
{
swap(v[nlow++], v[nhigh--]);
blow_is_change = true;
bhigh_is_change = true;
}
else
if(!blow_is_odd && !bhigh_is_odd)
{
nhigh--;
bhigh_is_change = true;
}
else
if(blow_is_odd && bhigh_is_odd)
{
nlow++;
blow_is_change = true;
}
else
{
nlow++;
nhigh--;
blow_is_change = true;
bhigh_is_change = true;
}
}
}
}
/****************************************************************************
@File Name: test.cpp
@Author: wangzhicheng
@mail: 2363702560@qq.com
@Created Time: Sat 28 Jan 2017 09:25:55 PM CST
@Revision Time:2017-01-29
****************************************************************************/
#include "PublicUtility.h"
#include <time.h>
#include <iostream>
#include <iterator>
using namespace publicutility;
template<typename ForwardIterator, typename UnaryPredicate>
ForwardIterator _partition(ForwardIterator first, ForwardIterator last, UnaryPredicate pred)
{
auto pos = first;
for(;first != last;++first)
{
if(pred(*first)) swap(*first, *pos++);
}
return pos;
}
int main()
{
const int N = 20;
srand(time(0));
vector<int>v;
for(int i = 0;i < N;i++)
{
int e = rand() % N;
cout << e << " ";
v.emplace_back(e);
}
cout << endl;
//PublicUtility::Odd_before_Even(v);
_partition(v.begin(), v.end(), [](int e)
{
return e & 1;
});
copy(v.begin(), v.end(), ostream_iterator<int>(cout, " "));
cout << endl;
return 0;
}
CC=g++
all:
$(CC) -std=c++11 -g -o test test.cpp PublicUtility.h PublicUtility.cpp
odd before even
最新推荐文章于 2025-04-13 22:11:28 发布
本文介绍了一种将数组中所有奇数元素置于偶数元素之前的排序算法实现,并通过示例展示了其使用方法。该算法利用双指针技术,分别从两端向中间遍历,高效完成奇偶元素的调整。

394

被折叠的 条评论
为什么被折叠?



