c++如何运用sort函数将学生成绩从高到低排序用冒泡排序带注释
以下是 C++ 冒泡排序从高到低的代码实现:
#include <iostream>
using namespace std;
void bubbleSort(int arr[], int n) {
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - i - 1; j++) {
if (arr[j] < arr[j + 1]) {
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
int main() {
int arr[] = { 5, 2, 8, 3, 1, 6 };
int n = sizeof(arr) / sizeof(arr[0]);
bubbleSort(arr, n);
cout << "从高到低排序后的数组为:";
for (int i = 0; i < n; i++) {
cout << arr[i] << " ";
}
cout << endl;
return 0;
}
输出结果为:
从高到低排序后的数组为:8 6 5 3 2 1
你都用sort了还要冒泡吗
你再问问题的时候 好像没有思考
```c++
#include<bits/stdc++.h>
using namespace std;
struct student{//定义学生的结构体
int score;
char name[50];
};
student stu[1010];
int cmp(student a,student b)
{
if(a.score!=b.score)
return a.score>b.score;//如果成绩不相同,则成绩好的先输出
else if(strcmp(a.name,b.name)!=0)
return strcmp(a.name,b.name)<0;//如果成绩相同,名字不相同,则按字典顺序输出。
}
int main()
{
int n;
cin>>n;//设置学生的数量
for(int i=0;i<n;i++)
{
cin>>stu[i].score>>stu[i].name;
}
sort(stu,stu+n,cmp);//sort函数进行排序
cout<<"排序之后的结果为"<<endl;
for(int i=0;i<n;i++)
{
cout<<stu[i].score<<" "<<stu[i].name<<endl;
}
return 0;
}
sort函数用于C++中,对给定区间(左闭右开)所有元素进行排序,默认为升序,也可进行降序排序。
sort函数包含在头文件为#include < algorithm >的c++标准库中。
语法:sort(start,end,cmp)
参数:
(1)start表示要排序数组的起始地址;
(2)end表示数组结束地址的下一位;
(3)cmp用于规定排序的方法,可不填,默认升序。