首页 > 试题广场 >

成绩排序

[编程题]成绩排序
  • 热度指数:184583 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 32M,其他语言64M
  • 算法知识视频讲解

查找和排序

题目:输入任意(用户,成绩)序列,可以获得成绩从高到低或从低到高的排列,相同成绩
都按先录入排列在前的规则处理。

示例:
jack      70
peter     96
Tom       70
smith     67

从高到低  成绩
peter     96
jack      70
Tom       70
smith     67

从低到高

smith     67

jack      70
Tom      70
peter     96


输入描述:
注意一个case里面有多组样例,请用循环处理输入
输入多行,先输入要排序的人的个数,然后输入排序方法0(降序)或者1(升序)再分别输入他们的名字和成绩,以一个空格隔开。


输出描述:
按照指定方式输出名字和成绩,名字和成绩之间以一个空格隔开
示例1

输入

3
0
fang 90
yang 50
ning 70

输出

fang 90
ning 70
yang 50
示例2

输入

3
1
fang 90
yang 50
ning 70
3
0
moolgouua 43
aebjag 87
b 67

输出

yang 50
ning 70
fang 90
aebjag 87
b 67
moolgouua 43

说明

第一组用例:
3
1
fang 90
yang 50
ning 70
升序排序为:
yang 50
ning 70
fang 90
第二组降序为:
aebjag 87
b 67
moolgouua 43  
#include<vector>
#include<string>
#include<iostream>
using namespace std;
int main(){
    vector<string> Name;
    vector<string>::iterator it1;
    vector<int> Score;
    vector<int>::iterator it2;
    int n=0;
    bool bs=true;
    while(cin>>n){
        cin>>bs;
        for(int i=0;i<n;i++){
            string name;
            int score;
            cin>>name>>score;
            it1=Name.begin();
            it2=Score.begin();
            while(it2!=Score.end()&&*it2<=score){
                it1++; it2++;
            }
            Name.insert(it1,name);
            Score.insert(it2,score);
        }
        if(bs)
            for(int i=0;i<n;i++)
                cout<<Name[i]<<' '<<Score[i]<<endl;
        else
            for(int i=n-1;i>=0;i--)
                cout<<Name[i]<<' '<<Score[i]<<endl;
        Name.clear();
        Score.clear();
    }
    return 0;
}
求大佬们解答,为啥这个代码通过率只有30%。。。。。讲真,看不出问题在哪orz........
失败的测试用例如下:
测试用例:
119 0 txrevyi 2 bshbreg 25 wx 71 xriyt 41 br 47 rbuqqvjic 100 ndpfojuz 34 eexjhre 21 rhictee 28 kanht 22 ejichusgdu 10 sp 65 ocuddtcdyd 83 qvh 75 uomeundng 5 fgswtdcm 88 inqkf 87 zfhnko 83 ojdpujwy 35 wzgyi 93 l 80 gdmfmjl 12 f 31 fdni 67 ytnlbefa 10 vdfpbizm 13 yror 91 e 14 cx 72 wxf 41 g 1 aln 80 zchmnjicb 28 mfk 64 fosazenls 87 dhzbotlm 32 pqvpag 82 myqqawf 42 nmwrcxloi 18 tz 67 hsyiykb 29 jlp 63 gnremcj 89 zsuzmnrvl 14 cos 5 dt 15 mqulq 31 bdox 19 hvhhblb 91 ogtdl 67 hy 45 wmwksobqs 44 dt 25 okatppi 4 txsqycc 89 djbmtfr 49 n 28 cca 43 kp 27 prnljksw 26 jb 6 zqrzs 8 bqoskic 7 mvgsdkg 2 dqvqxestjh 38 lnz 98 fedd 56 jauvkbai 98 ewpwdmegb 26 oeisemtup 16 lgn 46 ihznixw 3 oia 57 i 90 phqfg 60 oxkymaj 60 w 58 oawquiu 89 hfeprrtdar 24 wg 37 gwvprlhig 74 x 45 ntyo 90 rm 76 gbxphisqps 96 rrlbkwtrzc 88 gc 21 pefjinrzk 13 nuo 86 jnhsz 31 to 26 b 43 bueymur 18 jujwv 18 kf 0 l 61 dcryalrimv 20 oz 24 cpapxy 96 lndq 73 mjd 44 nrybszapvs 70 jip 77 olsttnf 64 ypb 75 zrksdy 17 jnng 87 y 0 ntckc 72 mraolqz 28 o 43 uutgjfh 66 fkedaaeagz 30 ajkmuprxvf 55 flxaqayh 33 hiqozhrcr 11 gcjg 93 jfuesm 55 xxwn 62 
对应输出应该为:
rbuqqvjic 100 lnz 98 jauvkbai 98 gbxphisqps 96 cpapxy 96 wzgyi 93 gcjg 93 yror 91 hvhhblb 91 i 90 ntyo 90 gnremcj 89 txsqycc 89 oawquiu 89 fgswtdcm 88 rrlbkwtrzc 88 inqkf 87 fosazenls 87 jnng 87 nuo 86 ocuddtcdyd 83 zfhnko 83 pqvpag 82 l 80 aln 80 jip 77 rm 76 qvh 75 ypb 75 gwvprlhig 74 lndq 73 cx 72 ntckc 72 wx 71 nrybszapvs 70 fdni 67 tz 67 ogtdl 67 uutgjfh 66 sp 65 mfk 64 olsttnf 64 jlp 63 xxwn 62 l 61 phqfg 60 oxkymaj 60 w 58 oia 57 fedd 56 ajkmuprxvf 55 jfuesm 55 djbmtfr 49 br 47 lgn 46 hy 45 x 45 wmwksobqs 44 mjd 44 cca 43 b 43 o 43 myqqawf 42 xriyt 41 wxf 41 dqvqxestjh 38 wg 37 ojdpujwy 35 ndpfojuz 34 flxaqayh 33 dhzbotlm 32 f 31 mqulq 31 jnhsz 31 fkedaaeagz 30 hsyiykb 29 rhictee 28 zchmnjicb 28 n 28 mraolqz 28 kp 27 prnljksw 26 ewpwdmegb 26 to 26 bshbreg 25 dt 25 hfeprrtdar 24 oz 24 kanht 22 eexjhre 21 gc 21 dcryalrimv 20 bdox 19 nmwrcxloi 18 bueymur 18 jujwv 18 zrksdy 17 oeisemtup 16 dt 15 e 14 zsuzmnrvl 14 vdfpbizm 13 pefjinrzk 13 gdmfmjl 12 hiqozhrcr 11 ejichusgdu 10 ytnlbefa 10 zqrzs 8 bqoskic 7 jb 6 uomeundng 5 cos 5 okatppi 4 ihznixw 3 txrevyi 2 mvgsdkg 2 g 1 kf 0 y 0 
你的输出为:
rbuqqvjic 100 jauvkbai 98

发表于 2019-01-21 12:05:16 回复(0)
更多回答
我想上一个Java8的写法,虽然对于少数量的排序,Java8的Steam体现不出什么优势。但还是供各位把玩一下Lambda
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class Main
{
    public static void main(String[] args)
    {
        Scanner scanner=new Scanner(System.in);
        while(scanner.hasNext())
        {
            int numPeople=scanner.nextInt();
            int option=scanner.nextInt();
             
            List<Student> stuList=new ArrayList<Student>();
            for(int i=0;i<numPeople;i++)
            {
                stuList.add(new Student(scanner.next(), scanner.nextInt()));
            }
             
            //降序
            if(option==0)
            {
                stuList.stream().sorted((e1,e2)->{
                    return e2.score - e1.score;
                 }).forEach(System.out::println);
            }
            else if(option==1)//升序
            {
                stuList.stream().sorted((e1,e2)->{
                    return e1.score - e2.score;
                }).forEach(System.out::println);
            }
        }
    }
}
 
class Student
{
    public String name;
    public int score;
    public Student(String name,int score)
    {
        this.name=name;
        this.score=score;
    }
    public String toString() {
        return this.name + " " + this.score;
    }
}


发表于 2019-03-17 23:56:37 回复(1)
#include<stdio.h>
int main()
{
    typedef struct sc
    {
        char name[100];
        int score;
    }sc;
    sc sc1[1000];
    int i,j,k,order,fen;
    sc scc;
    char a[100];
    while(scanf("%d%d",&i,&order)!=EOF)
    {
        for(j=0;j<i;j++)
            scanf("%s%d",sc1[j].name,&sc1[j].score);
        if(order==0)
            for(j=0;j<i;j++)
                for(k=0;k<i-j-1;k++)
                if(sc1[k].score<sc1[k+1].score)
            {
                scc=sc1[k];
                sc1[k]=sc1[k+1];
                sc1[k+1]=scc;
            }
                else ;
        else
            for(j=0;j<i;j++)
                for(k=0;k<i-j-1;k++)
                if(sc1[k].score>sc1[k+1].score)
            {
                scc=sc1[k];
                sc1[k]=sc1[k+1];
                sc1[k+1]=scc;
            }
            else ;
        for(j=0;j<i;j++)
            printf("%s %d\n",sc1[j].name,sc1[j].score);

    }
    return 0;
}
发表于 2018-01-11 16:58:54 回复(1)
#include <stdio.h>
#include <algorithm>
using namespace std;
struct E

    char name[100];
    int num;//用于标注录入顺序
    int score;
}buf[1000];
int direct;
bool cmp1(E a, E b)
    {
        if(a.score!=b.score) return a.score<b.score;
        else return a.num<b.num;//录入顺序
    }
bool cmp2(E a,E b)
    {
        if(a.score!=b.score) return a.score>b.score;
        else return a.num<b.num;//录入顺序
    }
int main()
{
    int n;
    while(scanf("%d",&n)!=EOF)
    {
        scanf("%d",&direct);
        for(int i=0;i<n;++i){
            scanf("%s %d",buf[i].name,&buf[i].score);
            buf[i].num=i;
        }
        if(direct==0)
            sort(buf,buf+n,cmp2);
        else if(direct==1)
            sort(buf,buf+n,cmp1);
        for(int i=0;i<n;++i)
        {
            printf("%s %d\n",buf[i].name,buf[i].score);
        }
    }
        return 0;
}
运行时间:3ms
占用内存:384k

发表于 2018-01-09 00:02:11 回复(5)
//供参考^-^~
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
using namespace std;

struct stu
{
	string name;
	int grade;
    stu(){name="";grade=0;}
};
int flag = 0;
vector<vector<string>>vec(1000);
bool compare(stu A, stu B)
{
	if (flag)
	{
		if (A.grade != B.grade)
			return A.grade<B.grade;
		for (int i = 0; i<vec[A.grade].size(); ++i)
		{
			if (A.name == vec[A.grade][i])
				return true;
			if (B.name == vec[A.grade][i])
				return false;
		}
	}
	else
	{
		if (A.grade != B.grade)
			return A.grade>B.grade;
		for (int i = 0; i<vec[A.grade].size(); ++i)
		{
			if (A.name == vec[A.grade][i])
				return true;
			if (B.name == vec[A.grade][i])
				return false;
		}
	}
	return false;
}

int main()
{
	int n = 0;
	
	while (cin>>n)
	{
		cin >> flag;
		vector<stu>numbers(n);
		for (int i = 0; i<n; ++i)
		{
			cin >> numbers[i].name >> numbers[i].grade;
			vec[numbers[i].grade].push_back(numbers[i].name);
		}
		sort(numbers.begin(), numbers.end(), compare);
		for (int i = 0; i < numbers.size(); ++i)
		{
			cout << numbers[i].name << " " << numbers[i].grade<<endl;
		}
        vec.clear();
		vec = vector<vector<string>>(1000);
	}
	return 0;
}

发表于 2016-11-30 11:50:39 回复(2)
#include<stdio.h>
struct student
{
 char name[20];
 int score;
};
int main()
{
 int num,choice,i,j;
 struct student temp;
 while(scanf("%d%d",&num,&choice)==2)
 {
  struct student stu[num];
  for(i=0;i<=num-1;i++)
  {
   scanf("%s%d",&stu[i].name,&stu[i].score);
  }
     if(choice==0)
     {
      for(i=0;i<=num-1;i++)
      {
       for(j=i+1;j<=num-1;j++)
       {
        if(stu[i].score<stu[j].score)
        {
         temp=stu[i];
         stu[i]=stu[j];
         stu[j]=temp;
     }
    }
   }
  }
  else if(choice==1)
  {
   for(i=0;i<=num-1;i++)
      {
       for(j=i+1;j<=num-1;j++)
       {
        if(stu[i].score>stu[j].score)
        {
         temp=stu[i];
         stu[i]=stu[j];
         stu[j]=temp;
     }
    }
   }
  }
  for(i=0;i<=num-1;i++)
  {
   printf("%s %d\n",stu[i].name,stu[i].score);
  }
 }
 return 0;
}
实在不理解为什么自己电脑能过,牛客怎么都过不了。这么简单的题目正确率这么低是有原因的吧……

发表于 2018-11-14 20:18:38 回复(3)
#include <iostream>
#include <vector>
#include <cstring>
#include <algorithm>
using namespace std;

struct Node {
    string name;
    int score; 
};

void initialAndSort(int numbers, int flag) // numbers 为每组的人员数量; flag=0 降序, flag=1 升序
{
    vector<Node> nums;
    while(numbers --)
    {
        Node node;
        cin >> node.name >> node.score;
        nums.push_back(node);
    }
    if(flag == 0) // 降序
    {
        stable_sort(nums.begin(), nums.end(),
         [](const Node &x, const Node &y)
         {
             return x.score > y.score;
         });
    }
    else if(flag == 1) // 升序
    {
        stable_sort(nums.begin(), nums.end(),
             [](const Node &x, const Node &y)
             {
                 return x.score < y.score;
             });
    }
    for(int i = 0; i < nums.size(); i++)
        cout << nums[i].name << " " << nums[i].score << endl;
}


int main() {
    int numbers, flag;
    while(cin >> numbers >> flag && numbers > 0)
    {
        initialAndSort(numbers, flag);
    }
    
    return 0;
}

发表于 2021-07-24 21:52:11 回复(0)
C语言版本,用两个数组分别存成绩和名字,再用插入排序进行排序,最后输出两个数组
#include <stdio.h>
#include <stdlib.h>

void sort_desc(int scores[], char **names , int n);
void sort_asc(int scores[], char **names , int n);

int main() {
    int n, type;
    while (scanf("%d%d", &n, &type) != EOF) {
        int *scores = malloc(sizeof(int) * n);
        char **names = (char**) malloc(sizeof(char*) * n);
        for (int i = 0; i < n; i++) {
            names[i] = (char*) malloc(sizeof(char) * 10);
            scanf("%s %d", &names[i][0], &scores[i]);
        }
        
        if (type == 0) {
            sort_desc(scores, names, n);
        } else {
            sort_asc(scores, names, n);
        }
        
        for (int i = 0; i < n; i++) {
            printf("%s %d\n", names[i], scores[i]);
        }
    }
    return 0;
}

// 插入排序
void sort_desc(int scores[], char **names , int n) {
    for (int i = 1; i < n; i++) {
        int j;
        for (j = i - 1; j >= 0 && scores[j] < scores[i]; j--) {
        }
        int i_score = scores[i];
        char *i_name = names[i];
        for (int k = i - 1; k > j; k--) {
            scores[k + 1] = scores[k];
            names[k + 1] = names[k];
        }
        scores[j + 1] = i_score;
        names[j + 1] = i_name;
    }
}

void sort_asc(int scores[], char **names , int n) {
    for (int i = 1; i < n; i++) {
        int j;
        for (j = i - 1; j >= 0 && scores[j] > scores[i]; j--) {
        }
        int i_score = scores[i];
        char *i_name = names[i];
        for (int k = i - 1; k > j; k--) {
            scores[k + 1] = scores[k];
            names[k + 1] = names[k];
        }
        scores[j + 1] = i_score;
        names[j + 1] = i_name;
    }
}



发表于 2021-02-27 08:50:29 回复(0)
 看了题目自然想到对结构体排序,开始习惯性用了sort(),但是sort用的快排,并不是稳定排序,无法满足先输入的排在前面,要改用stable_sort()能保证稳定排序。当然手写一个稳定排序也是可以的。
#include <iostream>
#include <algorithm>
using namespace std;

struct stu{
    char name[100];
    int grade;
}stus[1000];
int n,flag;

bool cmp(stu a,stu b){
    if(flag){
        return a.grade<b.grade;
    }
    else{
        return b.grade<a.grade;
    }
}

int main(){
    while(cin>>n){
        cin>>flag;
        for(int i=0;i<n;i++) cin>>stus[i].name>>stus[i].grade;
        stable_sort(stus,stus+n,cmp);
        for(int i=0;i<n;i++) cout<<stus[i].name<<' '<<stus[i].grade<<endl;
    }
    return 0;
}

发表于 2021-01-27 09:52:52 回复(0)

实在是没看出来错在哪里……
我能想到的样例自测都是对的,一提交就通过率为0……,服了………………

#include<iostream>
#include<algorithm>
#include<vector>
using namespace std;

int type;
struct Student
{
    string name;
    int grade,p;//p记录录入的顺序
    bool operator<(const Student& t)const
    {
        if(grade!=t.grade)
        {
            if(type==0)return grade>t.grade;
            if(type==1)return grade<t.grade;
        }
        return p<t.p;
    }
};
vector<Student>students;
int main()
{
    int n;
    cin>>n>>type;
    for(int i=0;i<n;++i)
    {
        string name;
        int grade;
        cin>>name>>grade;
        students.push_back({name,grade,i});
    }

    sort(students.begin(),students.end());
    for(auto& s:students)cout<<s.name<<' '<<s.grade<<endl;

    return 0;
}
发表于 2020-10-22 11:46:05 回复(0)
#include <cstdio>
#include <algorithm>
#include <string>
#include <vector>
using namespace std;
struct Record{
    string name;
    int score;
    int input_time;
};
int main(){
    int n,method;
    while(scanf("%d\n%d",&n,&method)!=EOF){
        vector<Record> records(n);
        for(int i=0;i<n;i++){
            char name[64];
            int score;
            scanf("%s %d",name,&score);
            records[i]=Record{string(name),score,i};
        }
        if(method)
            stable_sort(records.begin(),records.end(),
                        [](Record a,Record b){return a.score<b.score;});
        else
            stable_sort(records.begin(),records.end(),
                        [](Record a,Record b){return a.score>b.score;});
        for(const auto& x:records)
            printf("%s %d\n",x.name.c_str(),x.score);
    }
    return 0;
}
编辑于 2020-04-24 03:37:52 回复(0)
while 1:
    try:
        a,b = int(input()),int(input())
        print('\n'.join(map(lambda x:' '.join(x),\
                sorted([input().split() for i in range(a)],\
                key = lambda x:(-1) ** (b + 1) * int(x[1])))))
    except:
        break

编辑于 2020-03-23 12:00:36 回复(0)
分享一下前几次没有AC的原因:
第一次,没有循环输入,程序输入一组待测数据后就结束,自测的时候没问题,提交的时候显示输出为空。
第二次,改成循环输入,再次提交,只通过了60%的测试用例,提示数组越界,把sort()改成stable_sort(),提交还是只能通过60%的测试用例。
第三次,把数组的长度从100改成1000,提交上去通过了。我又把stable_sort()改成sort(),也能AC。

#include<iostream>
(720)#include<algorithm>
using namespace std;
struct student{
	int id;
	int grade;
	string name;
};
bool ascend(student a,student b){
	if(a.grade!=b.grade){
		return a.grade<b.grade;
	}
	else{
		return a.id<b.id;
	}
}

bool descend(student a,student b){
	if(a.grade!=b.grade){
		return a.grade>b.grade;
	}
	else{
		return a.id<b.id;
	}
}

int main(){
	student stu[1000];
	int N,flag;
	while(cin>>N>>flag){
		for(int i=0;i<N;i++){
			cin>>stu[i].name>>stu[i].grade;
			stu[i].id=i; 
		}
		if(flag){
			sort(stu,stu+N,ascend);
		}
		else{
			sort(stu,stu+N,descend);
		}
		for(int i=0;i<N;i++){
			cout<<stu[i].name<<" "<<stu[i].grade<<endl;
		}
	
	}
	return 0;	
}




发表于 2020-03-19 21:06:46 回复(0)
#include<iostream>
#
include<vector>
#include<cmath>
#
include<stack>
#include<sstream>
#
include<algorithm>
using namespace std;
struct stu{
    string name;
    int score;
};
bool cmp0(stu a,stu b){
    return a.score>b.score;
}
bool cmp1(stu a,stu b){
    return a.score<b.score;
}
int main(){
    int n,m;
    while(cin>>n>>m){
    stu s;
    vector<stu> v;
    for(int i=0;i<n;++i){
        cin>>s.name>>s.score;
        v.push_back(s);
    }
    if(m==0) sort(v.begin(),v.end(),cmp0);
    else sort(v.begin(),v.end(),cmp1);
    for(int i=0;i<n;++i){
        cout<<v[i].name<<" "<<v[i].score;
        printf("\n");
    }
    }
    return 0;
}
发表于 2020-03-06 10:05:02 回复(0)
#include <stdio.h>
#include <stdlib.h>

typedef struct student
{
    char name[20];
    int mark;
    int rank;
}student;
int cmp0(student *a,student *b)
{
    if(a->mark!=b->mark)return b->mark-a->mark;
    else return a->rank-b->rank;
}
int cmp1(student *a,student *b)
{
    if(a->mark!=b->mark)return a->mark-b->mark;
    else return a->rank-b->rank;
}
int main()
{
    int n,type;
    while(scanf("%d%d",&n,&type)!=EOF)
    {
        student stu[n];
        for(int i=0;i<n;i++)
        {
            scanf("%s%d",stu[i].name,&stu[i].mark);
            stu[i].rank=i;
        }
        if(type)qsort(stu,n,sizeof(student),cmp1);
        else qsort(stu,n,sizeof(student),cmp0);
        for(int i=0;i<n;i++)printf("%s %d\n",stu[i].name,stu[i].mark);
    }
}

编辑于 2020-02-12 22:57:55 回复(0)
#include<bits/stdc++.h>

using namespace std;

struct student
{
    string name;
    int score;
};

bool cmp0(const student &a, const student &b){
    return a.score > b.score;
}
bool cmp1(const student &a, const student &b){
    return a.score < b.score;
}

int main()
{
    int m, n;
    while(cin >> m >> n)
    {
        vector<student> stu;
        while(m--)
        {
            string a;
            int s;
            cin >> a >> s;
            student stu1;
            stu1.name = a;
            stu1.score = s;
            stu.push_back(stu1);
        }
        if(n == 0)
        {
            stable_sort(stu.begin(), stu.end(), cmp0);
        }
        else if(n == 1)
        {
            stable_sort(stu.begin(), stu.end(), cmp1);
        }
        for(vector<student>::iterator m = stu.begin(); m != stu.end(); m++)
        {
            cout << m->name << " " << m->score << endl;
        }
    }
    
}

发表于 2020-02-07 16:54:22 回复(0)
//再次感叹sort大法好,但是学到了一个很厉害的包头#include<bits/stdc++.h>
#include<iostream>
#include<algorithm>
using namespace std;
struct student {
	int id;
	char name[30];
	int grade;
};
bool compare_1(student a, student b) {
	if (a.grade<b.grade)
		return 1;
	else if (a.grade>b.grade)
		return 0;
	else {
		if (a.id<b.id)
			return 1;
		else
			return 0;
	}
}
bool compare_2(student a, student b) {
	if (a.grade>b.grade)
		return 1;
	else if (a.grade<b.grade)
		return 0;
	else {
		if (a.id<b.id)
			return 1;
		else
			return 0;
	}
}
int main() {
	int n, way;
	while (cin >> n >> way) {
		student* stu = new student[n];
		for (int i = 0; i<n; i++) {
			stu[i].id = i + 1;
			cin >> stu[i].name >> stu[i].grade;
		}
		if (way == 0)
			sort(stu, stu + n, compare_2);
		else
			sort(stu, stu + n, compare_1);
		for (int i = 0; i < n; i++)
			cout << stu[i].name << " " << stu[i].grade << endl;
	}
}

发表于 2020-01-11 20:48:57 回复(0)
//完了改一下类名
import java.util.Scanner;
public class Main2 {
    private static String[] names; //用names数组存储名字
    private static int[] grades; //用grades数组存储成绩
    private static boolean compare(int i, int j, int flag){
        return flag == 0 ? grades[i] > grades[j] : grades[i] < grades[j];
    }
    private static void exch(int i, int j){ //交换
        String tempS = names[j];
        names[j] = names[i];   //互换姓名
        names[i] = tempS;
        int tempG = grades[j];
        grades[j] = grades[i]; //互换成绩
        grades[i] = tempG;
    }
    public static void sort(int flag){
        //第一次:第二个人与第一个人比较;第二次:第三个人与第二个人比较;以此类推
        for(int i = 1; i < names.length; i++){
            //前提假如是升序(flag==1);
            //如果这个这个人成绩比他前一个人成绩小,那么【 j > 0 && compare(j,j - 1,flag)】这个条件才会满足
            //如果这个这个人成绩比他前一个人成绩大,那个直接不进入下边的for循环,直接他的下一个人和他开始比较
            for(int j = i; j > 0 && compare(j,j - 1,flag); j--){
                exch(j,j - 1); //去把他和他前一个人的成绩和姓名都互换(相当于只是换了一个位置)
            }
        }
    }
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        while(input.hasNext()){
            int n = input.nextInt();
            int flag = input.nextInt(); //flag为0降序,为1升序
            names = new String[n];
            grades = new int[n];
            for(int i = 0; i < n; i++){
                names[i] = input.next();
                grades[i] = input.nextInt();
            }
            sort(flag);
            //按格式输出即可
            for(int i = 0; i < n; i++){
                System.out.println(names[i] + " " + grades[i]);
            }
        }
    }
}

发表于 2019-11-27 17:33:42 回复(0)
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <algorithm>
#include <cmath>
#include <cctype>
#include <queue>

using namespace std;

inline int gi()
{
    int f = 1, x = 0;
    char c = getchar();
    while (c < '0' || c > '9')
    {
        if (c == '-') f = -1;
        c = getchar();
    }
    while (c >= '0' && c <= '9')
    {
        x = x * 10 + c - '0';
        c = getchar();
    }
    return f * x;
}

int n, fl, ans;
struct Node
{
    string name;
    int score, id;
} a[10005];

inline bool cmp(Node x, Node y)
{
    if (x.score != y.score) return x.score > y.score;
    return x.id < y.id;
}

inline bool cmp1(Node x, Node y)
{
    if (x.score != y.score) return x.score < y.score;
    return x.id < y.id;
}

int main()
{
    while (cin >> n >> fl)
    {
        for (int i = 1; i <= n; i++)
        {
            cin >> a[i].name;
            a[i].score = gi();
            a[i].id = i;
        }
        if (fl == 0) sort(a + 1, a + 1 + n, cmp);
        else sort(a + 1, a + 1 + n, cmp1);
        for (int i = 1; i <= n; i++)
        {
            cout << a[i].name << " " << a[i].score << endl;
        }
    }
    return 0;
}
可以直接使用c++自带的sort函数进行快速排序,不会超时,但是要自己写cmp自定义排序函数
发表于 2019-06-16 11:39:18 回复(0)
import java.util.Scanner;
import java.util.LinkedList;

// Java 桶排序算法复杂度,O(n) 
// 101个桶,分别保存 0~100分的学生名称, 然后按照ascOrDesc打印出来
public class Main {
  public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    while(scanner.hasNext()) {
      int stuNum = scanner.nextInt();
      int ascOrDesc = scanner.nextInt();
      LinkedList<String>[] numAndNameList = new LinkedList[101];
      for(int i = 0 ; i < stuNum; i++){
        String name = scanner.next();
        int scoreNum = scanner.nextInt();
        if (numAndNameList[scoreNum] == null) {
          numAndNameList[scoreNum] = new LinkedList<>();
        }
        numAndNameList[scoreNum].addLast(name);
      }
      if (ascOrDesc == 1) {
        for (int i = 0; i <= 100; i++) {
          if (numAndNameList[i] != null) {
            while (!numAndNameList[i].isEmpty()) {
              System.out.println(numAndNameList[i].pollFirst() + " " + i);
            }
          }
        }
      } else {
        for (int i = 100; i >= 0; i--) {
          if (numAndNameList[i] != null) {
            while (!numAndNameList[i].isEmpty()) {
              System.out.println(numAndNameList[i].pollFirst() + " " + i);
            }
          }
        }
      }
    }
  }
} 
发表于 2019-06-03 14:42:53 回复(1)
//第一次用,经验就是输入的时候用while(....!=EOF)比较不容易出错,之后是这道题目注意一下稳定排序
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
struct Student {
    char user[50];
    int score;
} stu[1000];
bool cmp1(Student a,Student b) {
    return a.score > b.score;
}
bool cmp2(Student a,Student b) {
    return a.score < b.score;
}
void highToLow(int n) {
    stable_sort(stu,stu+n,cmp1);
}
void lowToHigh(int n) {
    stable_sort(stu,stu+n,cmp2);
}
void input(int n) {
    for(int i = 0; i < n ; i++) {
        scanf("%s %d",stu[i].user,&stu[i].score);
    }
}
void output(int n) {
    for(int i = 0 ; i <n ; i++) {
        printf("%s %d\n",stu[i].user,stu[i].score);
    }
}
int main () {
    long n,m;
    while(scanf("%d",&n)!= EOF) {
        scanf("%d",&m);
        input(n);
        switch(m) {
            case 0:
                highToLow(n);
                break;
            case 1:
                lowToHigh(n);
                break;
            default:
                printf("请输入0或1,进行排序");
        }
        output(n);
    }
    return 0;
}
发表于 2019-03-02 16:07:10 回复(0)