只过了第一个点,问题出在冒泡排序,但是错哪了??

P5740 【深基7.例9】最厉害的学生

Aheaddd @ 2021-08-22 11:59:05

#include<iostream>
#include<string>
#include<algorithm>
using namespace std;
    struct student
    {
        string name;
        int score1;
        int score2;
        int score3;
        int sum = score1 + score2 + score3;
    };
    student stu[1010];

int main()
{
    int n, max = 0;
    cin >> n;
    for(int i=0;i<n;i++)
    {
        cin >> stu[i].name >> stu[i].score1 >> stu[i].score2 >> stu[i].score3;
    }
    for (int i = 0; i < n; i++)
    {

        if (stu[i].sum < stu[i + 1].sum)
        {
            struct student stu1= stu[i];
            stu[i] = stu[i + 1];
            stu[i + 1] = stu1;
        }
    }
    cout << stu[0].name << " " << stu[0].score1 << " " << stu[0].score2 << " " << stu[0].score3;
    return 0;

}

by linzhaoyumc @ 2021-08-22 12:01:15

for (int i = 0; i + 1 < n; i++)
    {

        if (stu[i].sum < stu[i + 1].sum)
        {
            struct student stu1= stu[i];
            stu[i] = stu[i + 1];
            stu[i + 1] = stu1;
        }
    }

改成这样?


by linzhaoyumc @ 2021-08-22 12:02:31

如果按你的写法,i+1 会越界


by linzhaoyumc @ 2021-08-22 12:03:25

@银河AI 这只是找最大值,冒泡排序就是把最大值移到一边


by 银河AI @ 2021-08-22 12:04:00

@linzhaoyumc 草我sb不好意思


by Aheaddd @ 2021-08-22 12:06:06

@linzhaoyumc 这个我想过,不过前面定义时是1010,题目n<=1000,n+1最大也就1001,怎么会越界呢?


by 听取MLE声一片 @ 2021-08-22 12:07:00

冒泡排序一层循环我大受震撼


by Aheaddd @ 2021-08-22 12:07:11

@Aheaddd 说错了,是i+1怎么会越界


by Aheaddd @ 2021-08-22 12:08:19

@听取MLE声一片 wocwoc???我脑子有病(:


by linzhaoyumc @ 2021-08-22 12:11:20

@Aheaddd 我悟了。。。

forn-2 开始,循环到 0 这样才是把最大值移到前面。其他的不用变。


by linzhaoyumc @ 2021-08-22 12:12:06

@听取MLE声一片 这明明是用冒泡的思路求最大值。。。


| 下一页