MST

星途 面试题库

面试题:C语言冒泡排序在复杂数据结构中的应用

假设有一个结构体数组,结构体包含学生的姓名(字符串)和成绩(整数),要求用C语言的冒泡排序按照成绩对学生信息进行降序排列,写出完整的代码实现。
14.6万 热度难度
编程语言C

知识考点

AI 面试

面试题答案

一键面试
#include <stdio.h>
#include <string.h>

// 定义学生结构体
typedef struct {
    char name[50];
    int score;
} Student;

// 交换两个学生的信息
void swap(Student *a, Student *b) {
    Student temp = *a;
    *a = *b;
    *b = temp;
}

// 冒泡排序函数,按照成绩降序排列
void bubbleSort(Student students[], int n) {
    int i, j;
    for (i = 0; i < n - 1; i++) {
        for (j = 0; j < n - i - 1; j++) {
            if (students[j].score < students[j + 1].score) {
                swap(&students[j], &students[j + 1]);
            }
        }
    }
}

int main() {
    // 初始化学生数组
    Student students[] = {
        {"Alice", 85},
        {"Bob", 92},
        {"Charlie", 78},
        {"David", 95}
    };
    int n = sizeof(students) / sizeof(students[0]);

    // 调用冒泡排序函数
    bubbleSort(students, n);

    // 输出排序后的学生信息
    printf("按照成绩降序排列后的学生信息:\n");
    for (int i = 0; i < n; i++) {
        printf("姓名: %s, 成绩: %d\n", students[i].name, students[i].score);
    }

    return 0;
}