c++ 排序算法程序

// paixu.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include "iostream"
#include "vector"
#include <algorithm>
using namespace std;

struct student
{
    string name;
    int score;
};
bool compare(int a,int b)
{
    return a<b;
}



int _tmain(int argc, _TCHAR* argv[])
{   
	std::vector <int> V;
    for(int i=0;i<10;i++)
    {
        V.push_back(10-i);
    }
    nth_element(V.begin(),V.begin()+10,V.end(),compare);
	for(int i=0;i<10;i++){
		 cout<<V[i]<<endl;
	}

	return 0;
}

nth_element函数的作用是:求一个容器中第n(大/小)的元素。函数参数:nth_element(first,nth,last,compare);这个函数的参数有些怪异,它是求[first,last]这个区间中第n(大/小)的元素,这点必须要注意,否则很容易写出这种形式(我就想当然的写了):nth_element(first,last,nth,compare);

这个函数看似没有什么用处,那么我们看一个例子:给你1000万个学生的信息(姓名,分数),输出分数排名在第k(总分高)学生的信息。
我们看到这个例题,首先会想到这个思路:先对所有学生的分数进行排序,然后输出student_book[k-1](下标从0开始)。但是一共有1000万个学生,其实我们只想知道一个学生的排名,对整个学生手册排序实在是太浪费了。

那么后面我们会想到:使用partial_sort对学生手册进行部分排序,然后再输出student_book[k-1],如果数据比较厉害,例如:1000万个学生,让你输出第1000万学生的信息。这就相当于让你全部排序,当然你也可以进行一些优化,将复杂度降到排序500万个数字。不过这其实还是太浪费了。此时,我们需要使用nth_element函数。
)
注意:nth_element函数会将第n(大/小)的元素放到第n的位置,且比第n(大/小)的元素会放到(右边/左边)。

我们看一下前一个例子的代码(1000万个学生也许太多了,对付100万个学生还是绰绰有余的):
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cstdlib>
#include <string>
#include <vector>
#include <iostream>
using namespace std;
struct student
{
string name;
int score;
};
bool compare(student a,student b)
{
return a.score>b.score;
}
int main()
{
vector <student> V;
int n,k;
cin>>n;
for(int i=0;i<n;i++)
{
student t;
cin>>t.name>>t.score;
V.push_back(t);
}
cin>>k;
nth_element(V.begin(),V.begin()+k,V.end(),compare);
cout<<V[k-1].name<<" "<<V[k-1].score<<endl;
return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值