题目(软件精P109题12):
输入5个学生的记录(每条记录包括学号和成绩), 组成记录数组, 然后按照成绩由高到低的次序输出. 排序方法采用选择排序
代码实现:
/* 输入5个学生的记录(每条记录包括学号和成绩), 组成记录数组, 然后按照成绩由高到低的次序输出. 排序方法采用选择排序 */
#include<iostream>
using namespace std;
const int size = 5;
typedef struct {
int id;
int score;
}Student;
void selectSort(Student* students, int n) {
for (int i = 0; i < n - 1; ++i) {
Student temp = students[i];
int loc = i;
for (int j = i + 1; j < n; ++j) {
if (students[j].score > students[loc].score) {
loc = j;
}
}
if (loc != i) {
students[i] = students[loc];
students[loc] = temp;
}
}
}
int main() {
Student students[size];
students[0] = {0, 60};
students[1] = {1, 70};
students[2] = {2, 90};
students[3] = {3, 30};
students[4] = {4, 50};
selectSort(students, size);
for (int i = 0; i < size; ++i) {
cout << students[i].id << "\t" << students[i].score << endl;
}
return 0;
}