- 论坛徽章:
- 0
|
本帖最后由 幻の上帝 于 2012-05-05 12:25 编辑
回复 10# sunny7476
python代码对应的C++代码也太挫了点……
替静态类型擦屁股的确得多费点劲,但也不至于这么罗嗦。瞎写了个:- template<typename T>
- list<T> merge(list<T> l1, list<T> l2){
- list<T> final;
- while(!l1.empty() && !l2.empty())l1.front() < l2.front() ? (final.push_back(l1.front()), l1.pop_front()) : (final.push_back(l2.front()), l2.pop_front());
- return final.splice(final.end(), l1), final.splice(final.end(), l2), final;
- }
- template<typename T>
- list<T> mergesort(list<T> l){
- if(l.size() <= 1)return l;
- auto mid(l.cbegin());
- advance(mid, l.size() / 2);
- return merge(mergesort(list<T>(l.cbegin(), mid)), mergesort(list<T>(mid, l.cend())));
- }
复制代码 对应的main:
- int main(){
- auto l(mergesort(list<int>{3, 5, 3, 6, 4, 7, 5, 7, 4}));
- for_each(l.begin(), l.end(), [](const int& i){cout<< i <<' ';});
- cout << endl;
- }
复制代码 再补个用list::merge的:- template<typename T>
- list<T> mergesort(list<T> l){
- if(l.size() <= 1)return l;
- const auto mid(next(l.cbegin(), l.size() / 2));
- auto ll(mergesort(list<T>(l.cbegin(), mid)));
- return ll.merge(mergesort(list<T>(mid, l.cend()))), ll;
- }
复制代码 (嘛……缩进莫名其妙乱了,再编辑一下好了。)
|
|