c++/java的sort()和cmp比较函数的编写

P1093 [NOIP2007 普及组] 奖学金

需要掌握c++/java(根据选择的参赛语言)的sort()和cmp比较函数的编写

java

导入util包,编写cmp类,实现接口Comparator,重写函数compare

编写排序规则:
i n t    c o m p a r e ( O b j e c t    o 1 ,    O b j e c t    o 2 )      返 回 一 个 基 本 类 型 的 整 型 如 果 要 按 照 升 序 排 序 , 则 o 1 小 于 o 2 , 返 回 − 1 ( 负 数 ) , 相 等 返 回 0 , o 1 大 于 o 2 返 回 1 ( 正 数 ) 如 果 要 按 照 降 序 排 序 则 o 1 小 于 o 2 , 返 回 1 ( 正 数 ) , 相 等 返 回 0 , o 1 大 于 o 2 返 回 − 1 ( 负 数 ) int~~compare(Object~~o1,~~Object~~o2) ~~~~返回一个基本类型的整型\\ 如果要按照升序排序,\\ 则o1小于o2,返回-1(负数),相等返回0,o1大于o2返回1(正数)\\ 如果要按照降序排序\\ 则o1 小于o2,返回1(正数),相等返回0,o1大于o2返回-1(负数)\\ int  compare(Object  o1,  Object  o2)    o1o210o1o21o1o210o1o21
可以使用Integer.compare()和Long.compare()等封装好的方法,默认是升序排序,若要降序,前面加一个负号即可

e.g:

return Integer.compare(a, b); // 比较a和b以此升序排列
return -Integer.compare(a, b); //比较a和b以此降序排列
Arrays.sort(stu,new cmp());
import java.util.Arrays;
import java.util.Comparator;
import java.util.Scanner;

public class Main{
	static int n;
	static int yw,sx,yy;
	static Stu[] stu;
	public static void main(String[] args) {
		Scanner in = new Scanner(System.in);
		n = in.nextInt();
		stu = new Stu[n];
		for(int i=0;i<n;i++) {
			yw = in.nextInt();
			sx = in.nextInt();
			yy = in.nextInt();
			stu[i] = new Stu(i+1, yw, sx, yy);
		}
		Arrays.sort(stu,new cmp());
		for(int i=0;i<Math.min(5, n);i++) {
			System.out.println(stu[i].no+" "+stu[i].all);
		}
	}
}
class Stu{
	public int no;
	public int yw;
	public int sx;
	public int yy;
	public int all;
	public Stu(int no, int yw, int sx, int yy) {
		this.no = no;
		this.yw = yw;
		this.sx = sx;
		this.yy = yy;
		this.all = yw+sx+yy;
	}
}
class cmp implements Comparator<Stu>{
	public int compare(Stu a, Stu b) {
		if(a.all!=b.all) {
			return -Integer.compare(a.all, b.all);
		}else {
			if(a.yw!=b.yw) {
				return -Integer.compare(a.yw, b.yw);
			}else {
				return Integer.compare(a.no, b.no);
			}
		}
	}
}

c++

导入<algorithm>头文件,编写函数,函数返回值为bool ,传入待比较的两个参数

return a>b //比较a和b以此从大到小(降序)排列
return a<b //比较a和b以此从小到大(升序)排列
sort(stu,stu+n,cmp);
#include <iostream>
#include <stdio.h>
#include <algorithm>
using namespace std;

int n;
struct Stu{
    int no;
    int yw;
    int sx;
    int yy;
    int all;

}stu[301];
bool cmp(const Stu a, const Stu b){
    if(a.all!=b.all) return a.all>b.all;
    else if(a.yw!=b.yw) return a.yw>b.yw;
    else return a.no<b.no;
}
int main(){
    cin>>n;
    for(int i=0;i<n;i++){
        cin>>stu[i].yw>>stu[i].sx>>stu[i].yy;
        stu[i].no = i+1;
        stu[i].all = stu[i].yw+stu[i].sx+stu[i].yy;
    }
    sort(stu,stu+n,cmp);
    for(int i=0;i<min(5,n);i++)
        cout<<stu[i].no<<" "<<stu[i].all<<endl;
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值