泛型归并排序

#define SENTINEL_CARD (-1)

#include <vector>

#include <algorithm>

#include <iterator>

#include <functional>

#include <iterator>

template<

class bidirectional_iterator,

template <class> class less_equal_compare = std::less_equal

>

class merge_sort_functor

{

public:

void operator()(

bidirectional_iterator p,

bidirectional_iterator r)const

{

size_t diff = distance(p,r);

if(diff <=1)

return;

if(diff >0)

{

bidirectional_iterator q = p;

advance(q, diff/2);

this->operator ()(p, q);

this->operator ()(q, r);

merge(p, q, r);

}

}

private:

void merge( bidirectional_iterator first,

bidirectional_iterator middle,

bidirectional_iterator last)const

{

using namespace std;

typedef less_equal_compare<bidirectional_iterator::value_type> le;

le le_comparer;

size_t n1 = distance(first, middle);

size_t n2 = distance(middle, last);

std::vector<int> L(first,middle);

std::vector<int> R(middle,last);

L.push_back(SENTINEL_CARD);

R.push_back(SENTINEL_CARD);

std::vector<int>::iterator i=L.begin(), j=R.begin();

for(bidirectional_iterator k=first; distance(k,last)>=0; ++k)

{

if(*i == SENTINEL_CARD)

{

std::copy(j, --R.end(), k);

return;

}

if(*j == SENTINEL_CARD)

{

std::copy(i, --L.end(), k);

return;

}

if( le_comparer(*i,*j) )

*k = *i++;

else

*k = *j++;

}

}

};

测试程序

int b[]={345,67,56,6,4567467,65768,7686,34635,67,57678,235};

vector<int> vi(b,b+sizeof(b)/sizeof(int));

list<int> li(b,b+sizeof(b)/sizeof(int));

merge_sort(b, 0, sizeof(b)/sizeof(int));

merge_sort_functor<vector<int>::iterator, std::less_equal>()

(vi.begin(), vi.end());

merge_sort_functor<list<int>::iterator, std::greater>()

(li.begin(), li.end());

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值