# 泛型插入排序

382人阅读 评论(0)

#pragma once

#include <iterator>

#include <functional>

template<

class bidirectional_iterator,

template<class> class greater_compare = std::greater

>

class insertion_sort_functor

{

public:

bool operator()(bidirectional_iterator first, bidirectional_iterator last)const

{

typedef bidirectional_iterator::value_type value_type;

typedef greater_compare<value_type> gc;

gc gc_comparer;

bidirectional_iterator j = next_iterator(first);

for( ; j!=last ; ++j)

{

value_type key = *j;

bidirectional_iterator i = last_iterator(j);

while(std::distance(first,i)>0 && gc_comparer(*i,key) )

{

*next_iterator(i) = *i;

--i;

}

if(i == first && gc_comparer(*i,key))

{

*next_iterator(i) = *i;

*i = key;

continue;

}

*next_iterator(i)= key;

}

return true;

}

private:

bidirectional_iterator last_iterator(const bidirectional_iterator& i)const

{

bidirectional_iterator j(i);

return --j;

}

bidirectional_iterator next_iterator(const bidirectional_iterator& i)const

{

bidirectional_iterator j(i);

return ++j;

}

};

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

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

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

insertion_sort(a ,sizeof(a)/sizeof(int));

insertion_sort_functor<vector<int>::iterator, std::less>()

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

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

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

0
0

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