首页 > 代码库 > 分治法
分治法
1)归并排序
//Merge sort template<typename T> list<T> mergeSort(const list<T>& source); template<typename T> list<T> mergeSort(const list<T>& source) { list<T> ret; if(source.size()==1) { ret=source; } else if(source.size()==2) { typename list<T>::const_iterator firstit=source.begin(); T firstvalue=*firstit; typename list<T>::const_iterator secondit=++firstit; T secondvalue=*secondit; if(firstvalue<=secondvalue) { ret=source; } else { ret.push_back(secondvalue); ret.push_back(firstvalue); } } else { unsigned int count_list=source.size(); unsigned int modN= count_list%2; unsigned int subret=count_list/2; typename list<T>::const_iterator it=source.begin(); list<T> leftS; list<T> rightS; for(int i=0;i!=subret+modN;++i) { leftS.push_back(*it); ++it; } for(int i=0;i!=subret;++i) { rightS.push_back(*it); ++it; } leftS=mergeSort(leftS);//lefts 传递const 引用,效率和安全,不会改动.返回对象.lefts被copy赋值函数处理. rightS=mergeSort(rightS); typename list<T>::const_iterator lefttop=leftS.begin(); typename list<T>::const_iterator righttop=rightS.begin(); while(lefttop!=leftS.end() || righttop!=rightS.end()) { // check each top if(*lefttop<=*righttop) { ret.push_back(*lefttop); ++lefttop; } else { ret.push_back(*righttop); ++righttop; } } if(lefttop!=leftS.end()) { //push no process data for(lefttop;lefttop!=leftS.end();++lefttop) { ret.push_back(*lefttop); } } else if(righttop!=rightS.end()) { for(righttop;righttop!=rightS.end();++righttop) { ret.push_back(*righttop); } } return ret; } return ret; }
分治法
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。