笔试面试之奇偶partition

输入一个整数数组,调整数组中数字的顺序,使得所有奇数位于数组的前半部分,所有偶数位于数组的后半部分。要求时间复杂度为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/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值