作业: 根据学生数组元素的x+y的值 对 学生数组stus 进行排序,编写合适的bubble_sort_stu(stus, len1);
bubble_sort_stu(stus, len1,cmp) cmp是一个判断学生大小的函数,自己根据需要设计。
void bubble_sort(int arr[], int len, bool(*p)(int, int)) {//编写这个函数,对学生结构体数组进行排序
int i, j, temp;
for (i = 0; i < len - 1; i++)
for (j = 0; j < len - 1 - i; j++)
// if (arr[j] > arr[j + 1])
if(p(arr[j], arr[j + 1]))
{
temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
void bubble_sort(int arr[], int len) {
int i, j, temp;
for (i = 0; i < len - 1; i++)
for (j = 0; j < len - 1 - i; j++)
if (arr[j] > arr[j + 1]) {
temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
void bubble_sort_stu(student arr[], int len) { //编写这个函数,对学生结构体数组进行排序
int i, j, temp;
for (i = 0; i < len - 1; i++)
for (j = 0; j < len - 1 - i; j++)
if (arr[j] > arr[j + 1]) {
temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
struct student
{
int x; int y;
};
int main() {
// int arr[] = { 22, 34, 3, 32, 82, 55, 89, 50, 37, 5, 64, 35, 9, 70 };
student stus[] = { { 1, 2 }, { 3, 4 }, { 5, 6 } };
看起来你想使用冒泡排序算法对一个student
结构体数组进行排序,根据它们的x
和y
值之和。下面是一种修改bubble_sort_stu
函数以实现此目的的方法:
#include <stdbool.h>
struct student {
int x;
int y;
};
bool cmp(struct student a, struct student b) {
return (a.x + a.y) > (b.x + b.y);
}
void bubble_sort_stu(struct student arr[], int len, bool(*p)(struct student, struct student)) {
int i, j;
struct student temp;
for (i = 0; i < len - 1; i++)
for (j = 0; j < len - 1 - i; j++)
if (p(arr[j], arr[j + 1])) {
temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
int main() {
struct student stus[] = { {1, 2}, {3, 4}, {5, 6} };
int len = sizeof(stus) / sizeof(stus[0]);
bubble_sort_stu(stus, len, cmp);
return 0;
}
在这个例子中,我们定义了一个cmp
函数,它接受两个student
结构体作为参数,并在第一个学生的x
和y
值之和大于第二个学生的x
和y
值之和时返回true
。然后我们将这个函数作为参数传递给bubble_sort_stu
函数,在排序时用它来比较学生。