转:C++学习【原创】归并排序(inplace_merge函数的应用)

inplace_merge函数的作用和merge函数差不多,只不过是在一个容器中进行归并。函数参数:inplace_merge(first,mid,last,compare);//将[first,mid) 和 [mid,last)这两个区间进行归并成一个有序序列。

注意:[first,mid)和[mid,last)都要呈升序或降序排列!

还记得归并排序的写法么?归并排序利用了分治的思想,将一个容器分割,然后再将它们一个个合并起来,最后形成一个有序的序列。归并排序的核心代码就在于合并两个序列,不过STL的开发人员已经为我们完成了,我们直接调用就可以了。

例题:给你n个学生的信息,根据它们的分数从小到大排序,注意:如果遇到分数相等的同学,按照原来的顺序排列。
因为归并排序是一个稳定的排序,所以我们不需要理睬注意事项。
代码:
#include <iostream>
#include <cstdio>
#include <vector>
#include <cstdlib>
#include <cstring>
#include <algorithm>
#include <string>
using namespace std;
struct student
{
    string name;
    int score;
    bool operator <(const student &t) const
    {
        return score<t.score;
    };
};
typedef vector <student> ::iterator Iter;
vector <student> V;
void merge_sort(Iter a,Iter b)
{
    if(a>=b) return ;
    Iter mid=((a-V.begin())+(b-V.begin()))/2+V.begin();
    merge_sort(a,mid);
    merge_sort(mid+1,b);
    inplace_merge(a,mid,b,less<student>());
}
int main()
{
    int n;
    cin>>n;
    for(int i=0;i<n;i++)
    {
        student t;
        cin>>t.name>>t.score;
        V.push_back(t);
    }
    merge_sort(V.begin(),V.end());
    for(Iter it=V.begin();it!=V.end();it++)
        cout<<it->name<<" "<<it->score<<endl;
    return 0;
}

转载于:https://www.cnblogs.com/cchun/archive/2012/05/26/2519394.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值