- 使用sort进行排序,以n台机器为例,每一个机器有最长的工作时间和机器等级;那么这里需要注意的是,一个机器对应的工作时间和机器等级是相互绑定的,所以这里使用结构体,结构体包含两个成员,一个是机器的工作时间,一个是机器的等级;那么对于排序,我们按照机器时间优先进行排序,在机器时间相同的情况下,再按照机器等级进行排序;同理按照这种方法可以分为优先级1>优先级2>…>优先级n进行排序,只需要在cmp函数中修改对应的即可,而且sort函数进行排序的时间复杂度为n*log2n,比冒泡之类的排序算法效率要高,sort函数包含在头文件为#include的c++标准库中。
#include <bits/stdc++.h>
using namespace std;
const int maxn = 1e5 + 10;
struct node
{
int costTime, grade;
}machine[maxn];
int cmp(node a, node b)
{
//这里的排序先以时间为优先进行排序,如果时间相等的话,则以等级
if(a.costTime == b.costTime)return a.grade > b.grade;
return a.costTime > b.costTime;
}
int main()
{
int numberOfMachines;
scanf("%d", &numberOfMachines);
for(int i = 0; i < numberOfMachines; i ++)scanf("%d %d", &machine[i].costTime, &machine[i].grade);
printf("排序之前: \n");
for(int i = 0; i < numberOfMachines; i ++)printf("%d %d\n", machine[i].costTime, machine[i].grade);printf("\n");
sort(machine, machine+numberOfMachines, cmp);
printf("排序之后: \n");
for(int i = 0; i < numberOfMachines; i ++)printf("%d %d\n", machine[i].costTime, machine[i].grade);printf("\n");
return 0;
}
输出结果:
排序之前:
99 1
100 1
100 2
99 2
100 3
排序之后:
100 3
100 2
100 1
99 2
99 1
可以注意到时间为第一优先级,等级为第二优先级
三个优先级可以按下面去写
先按a值升序排列,如果a值相同,再按b值降序排列,如果b还相同,就按c降序排列。就可以写一个比较函数:
bool cmp(node x,node y)
{
if(x.a!==y.a) return x.a<y.a;
if(x.b!==y.b) return x.b>y.b;
return x.c>y.c;
}
- 使用sort进行简单的升序和降序
#include <bits/stdc++.h>
using namespace std;
const int maxn = 1e5 + 10;
int a[maxn];
int n;
int cmp(int a, int b)
{
//return a > b;//降序
return a < b;//升序
}
int main()
{
scanf("%d", &n);
for(int i = 0; i < n; i ++)scanf("%d", &a[i]);
printf("排序之前: \n");
for(int i = 0; i < n; i ++)printf("%d ", a[i]);printf("\n");
sort(a, a+n, cmp);
printf("排序之后: \n");
for(int i = 0; i < n; i ++)printf("%d ", a[i]);printf("\n");
return 0;
}
输出结果:这里只需要改变cmp函数,即可完成升序或者降序的操作,非常方便
排序之前:
1 3 4 5 6 3 6 7 8 2
排序之后:
1 2 3 3 4 5 6 6 7 8
-
标准库里已经有现成的了,就在functional里,include进来就行了。functional提供了一堆基于模板的比较函数对象。它们是(看名字就知道意思了):equal_to、not_equal_to、greater、greater_equal、less、less_equal。对于这个问题来说,greater和less就足够了,直接拿过来用:
升序:sort(begin,end,less());
降序:sort(begin,end,greater()).
比如:
#include<iostream>
#include<algorithm>//因为用了sort()函数
#include<functional>//因为用了greater<int>()
伪代码: 进行降序
sort(a,a+20,greater<int>());