c语言

C语言中如何对结构体数组进行逆序排序

小樊
86
2024-08-27 04:49:15
栏目: 编程语言

在C语言中,要对结构体数组进行逆序排序,你可以使用以下方法:

  1. 首先定义一个结构体类型,例如:
typedef struct {
    int id;
    char name[50];
} Student;
  1. 创建一个结构体数组并填充数据:
Student students[] = {
    {1, "Alice"},
    {2, "Bob"},
    {3, "Charlie"},
    {4, "David"}
};
int n = sizeof(students) / sizeof(students[0]); // 计算数组长度
  1. 编写一个交换结构体元素的函数:
void swap(Student *a, Student *b) {
    Student temp = *a;
    *a = *b;
    *b = temp;
}
  1. 使用循环逆序排序结构体数组:
for (int i = 0; i < n / 2; i++) {
    swap(&students[i], &students[n - 1 - i]);
}
  1. 打印逆序排序后的结构体数组:
for (int i = 0; i < n; i++) {
    printf("ID: %d, Name: %s\n", students[i].id, students[i].name);
}

完整代码示例:

#include<stdio.h>

typedef struct {
    int id;
    char name[50];
} Student;

void swap(Student *a, Student *b) {
    Student temp = *a;
    *a = *b;
    *b = temp;
}

int main() {
    Student students[] = {
        {1, "Alice"},
        {2, "Bob"},
        {3, "Charlie"},
        {4, "David"}
    };
    int n = sizeof(students) / sizeof(students[0]);

    for (int i = 0; i < n / 2; i++) {
        swap(&students[i], &students[n - 1 - i]);
    }

    for (int i = 0; i < n; i++) {
        printf("ID: %d, Name: %s\n", students[i].id, students[i].name);
    }

    return 0;
}

运行此代码将输出逆序排序后的结构体数组。

0
看了该问题的人还看了