机试指南第二章-经典入门-排序例题自解

例2.1 排序

时间限制:1秒  空间限制:65536K

AC代码

#include<cstdio>
#include<algorithm>

using namespace std;
int main()
{
    int n;
    while (scanf("%d", &n) != EOF)
    {
        int a[105];
        for (int i = 0; i < n; i++) scanf("%d", &a[i]);
        sort(a, a + n);
        for (int i = 0; i < n; i++)printf("%d ", a[i]);
        printf("
");
    }
    return 0;
}

冒泡排序解法

#include<cstdio>
#include<algorithm>

using namespace std;
int main()
{
    int n;
    while (scanf("%d", &n) != EOF)
    {
        int a[105];
        for (int i = 0; i < n; i++) scanf("%d", &a[i]);
        for (int i = 0; i < n; i++)
        {
            for (int j = 0; j < n - i - 1; j++)
            {
                if (a[j] > a[j + 1])
                {
                    int t = a[j];
                    a[j] = a[j + 1];
                    a[j + 1] = t;
                }
            }
        }
        for (int i = 0; i < n; i++)printf("%d ", a[i]);
        printf("
");
    }
    return 0;
}

例2.2 成绩排序

时间限制:1秒  空间限制:65536K

AC代码

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

struct Student
{
    char name[101];
    int age;
    int score;
};

bool cmp(Student x, Student y)
{
    if (x.score == y.score)
    {
        if(strcmp(x.name,y.name)==0)return x.age<y.age;
        else return strcmp(x.name,y.name)<0;
    }
    else return x.score < y.score;
}

int main()
{
    int n;
    Student stu[1001];//保存我们将要排序的数据
    while (cin >> n)
    {
        for (int i = 0; i < n; i++)
        {
            cin >> stu[i].name >> stu[i].age >> stu[i].score;
        }
        sort(stu, stu + n, cmp);
        for (int i = 0; i < n; i++)
            cout << stu[i].name << " " << stu[i].age << " " << stu[i].score << endl;
    }
    return 0;
}
原文地址:https://www.cnblogs.com/yun-an/p/11027678.html