输入一个整数数组,调整数组中数字的顺序,使得所有奇数位于数组的前半部分,所有偶数位于数组的后半部分。要求时间复杂度为O(n)。
方法一:遍历数组统计出奇数偶数个数,再申请一个数组,放置即可,时复o(n),空复o(n)
方法二:从开头遍历,遇到偶数则从后面寻找最接近的一个奇数交换,若找不到,则返回完成。时复o(n方)
方法三:类似于quick sort 从两头向中间遍历,低指针找偶数,高指针找奇数,找到后交换,直至低指针>=高指针,时复o(n)
方法四:STL中的stable_partition算法
方法三
bool isEven(int n)
{
return (n & 1) == 0;
}
void Reorder(int *pData, unsigned
int length, bool (*func)(int))
{
if(pData
== NULL || length == 0)
return;
int
*pBegin = pData;
int *pEnd
= pData + length - 1;
while(pBegin < pEnd)
{
// if
*pBegin does not satisfy func, move forward
if(!func(*pBegin))
{
pBegin ++;
continue;
}
// if
*pEnd does not satisfy func, move backward
if(func(*pEnd))
{
pEnd --;
continue;
}
// if
*pBegin satisfy func while *pEnd does not,
// swap
these integers
int
temp = *pBegin;
*pBegin = *pEnd;
*pEnd = temp;
}
}
void ReorderOddEven(int *pData, unsigned int length)
{
if(pData == NULL || length == 0)
return;
Reorder(pData, length, isEven);
}
方法四:STL的partition源码
template<typename _BidirectionalIter, typename _Predicate>
_BidirectionalIter
__partition(_BidirectionalIter __first, _BidirectionalIter __last,
_Predicate __pred,
bidirectional_iterator_tag)
{
while (true) {
while (true)
if (__first == __last)
return __first;
else if (__pred(*__first))
++__first;
else
break;
--__last;
while (true)
if (__first == __last)
return __first;
else if (!__pred(*__last))
--__last;
else
break;
iter_swap(__first, __last);
++__first;
}
}
这个算法的结束条件?
转贴自:http://zhedahht.blog.163.com/blog/static/25411174200741295930898/
823

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



