PAT乙 1004 成绩排名 C++ 快速排序
题目
读入 n(>0)名学生的姓名、学号、成绩,分别输出成绩最高和成绩最低学生的姓名和学号。
输入格式:
每个测试输入包含 1 个测试用例,格式为
第 1 行:正整数 n
第 2 行:第 1 个学生的姓名 学号 成绩
第 3 行:第 2 个学生的姓名 学号 成绩
… … …
第 n+1 行:第 n 个学生的姓名 学号 成绩
其中姓名和学号均为不超过 10 个字符的字符串,成绩为 0 到 100 之间的一个整数,这里保证在一组测试用例中没有两个学生的成绩是相同的。
输出格式:
对每个测试用例输出 2 行,第 1 行是成绩最高学生的姓名和学号,第 2 行是成绩最低学生的姓名和学号,字符串间有 1 空格。
输入样例:
3
Joe Math990112 89
Mike CS991301 100
Mary EE990830 95
输出样例:
Mike CS991301
Joe Math990112
思路
题目容易看懂,只需要构建一个结构体变量Student,再构建一个Student类型的vector。因为方便动态拓展,然后根据各个Studen型变量t的score进行排序。最后输出最高和最低位。
代码
#include<iostream>
#include<string>
#include<vector>
using namespace std;
struct Student
{
string name;
string id;
int score;
};
int Partiotion(vector<Student>&S, int low, int high)//一次划分
{
Student pivot = S[low];
while (low < high)
{
while (low < high && S[high].score >= pivot.score) --high;
S[low] = S[high];
while (low < high && S[low].score <= pivot.score) ++low;
S[high] = S[low];
}
S[low] = pivot;
return low;
}
void quickSort(int low, int high, vector<Student>&S)//快速排序,升序
{
if (low < high)
{
int pivotpos = Partiotion(S, low, high);
quickSort(low, pivotpos - 1, S);
quickSort(pivotpos + 1, high, S);
}
}
int main()
{
int n;
cin >> n;
vector<Student>S(1);
S.resize(n);
for (int i = 0; i < n; i++)
{
cin >> S[i].name >> S[i].id >> S[i].score;
}
quickSort(0, n-1, S);
cout << S[n - 1].name <<" "<< S[n - 1].id << endl;//最高
cout << S[0].name << " "<< S[0].id ;//最低
return 0;
}
心得
1.
学到了vector做形参的三种方式
传值 fun(vector< int>S)
传引用fun(vector< int >&S)
传指针fun(vector< int>*S)
没有和数组一样采用方括号当形参 fun(vector< int>S[])
2.
一个结构体是可以用另一个结构体通过=赋值的。
3
快速排序就是根据选的枢轴元素进行一次划分,把数组中的排序分为左边的数都小于等于它,右边的数都大于等于它。然后对左右两边的数组进行同样的划分,直到只有一个元素为止。
int Partiotion(vector&S, int low, int high)//一次划分
{
Student pivot = S[low]; //划分时使low指向的节点位枢轴节点,也等于记录了枢轴节点的值,可以直接往里面写入元素
while (low < high)
while (low < high && S[high].score >= pivot.score) --high;//从尾部开始扫描小于h枢轴的元素
S[low] = S[high];//找到了就将其和low指向的元素换位
while (low < high && S[low].score <= pivot.score) ++low;//从头部开始扫描大于h枢轴的元素
S[high] = S[low];//找到了就将其和low指向的元素换位
}
S[low] = pivot;在最后将枢轴元素放到大小分界的位置
return low;//返回下次划分的位置
}
void quickSort(int low, int high, vector&S)//快速排序就是进行进行递归多次划分
{
if (low < high)//递归结束条件
{
int pivotpos = Partiotion(S, low, high);
quickSort(low, pivotpos - 1, S);//对左边划分
quickSort(pivotpos + 1, high, S);//对右边划分
}
}