# 泛型归并排序

384人阅读 评论(0)

#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;

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());

0
0

* 以上用户言论只代表其个人观点，不代表CSDN网站的观点或立场
个人资料
• 访问：32729次
• 积分：583
• 等级：
• 排名：千里之外
• 原创：22篇
• 转载：15篇
• 译文：0篇
• 评论：11条
文章分类
阅读排行
评论排行
最新评论
其他人的blog