Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Lập Trình C

Lưu trữ và sắp xếp hồ sơ sinh viên theo tên trong C

Lưu hồ sơ sinh viên (ID, tên, phần trăm) vào struct và sắp xếp theo tên dùng qsort().

Ví dụ

Đầu vào - 5 sinh viên: Nupur, Akash, Yash, Jyoti, Ramlal

Đầu ra - Sắp xếp theo tên: Akash, Jyoti, Nupur, Ramlal, Yash

Phương pháp

  • Định nghĩa struct Student {id, name, percentage}
  • Hàm so sánh comparator dùng strcmp()
  • Gọi qsort(arr, n, sizeof(Student), comparator)

Chương trình mẫu

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

struct Student {
    int id;
    char *name;
    int percentage;
};

int comparator(const void *a, const void *b) {
    return strcmp(((struct Student*)a)->name, ((struct Student*)b)->name);
}

int main() {
    int n = 5;
    struct Student arr[5] = {
        {1, "Nupur", 98},
        {2, "Akash", 75},
        {3, "Yash", 62},
        {4, "Jyoti", 87},
        {5, "Ramlal", 80}
    };
    
    printf("Chưa sắp xếp:\n");
    for (int i = 0; i < n; i++)
        printf("ID=%d, Name=%s, %%=%d\n", arr[i].id, arr[i].name, arr[i].percentage);
    
    qsort(arr, n, sizeof(struct Student), comparator);
    
    printf("\nĐã sắp xếp theo tên:\n");
    for (int i = 0; i < n; i++)
        printf("ID=%d, Name=%s, %%=%d\n", arr[i].id, arr[i].name, arr[i].percentage);
    
    return 0;
}

Kết quả

Chưa sắp xếp:
ID=1, Name=Nupur, %=98
ID=2, Name=Akash, %=75
ID=3, Name=Yash, %=62
ID=4, Name=Jyoti, %=87
ID=5, Name=Ramlal, %=80

Đã sắp xếp theo tên:
ID=2, Name=Akash, %=75
ID=4, Name=Jyoti, %=87
ID=1, Name=Nupur, %=98
ID=5, Name=Ramlal, %=80
ID=3, Name=Yash, %=62