实现思路
- 定义一个比较函数,用于比较两个结构体指针指向的结构体中
pages
成员的大小。
- 使用
qsort
函数,它是C标准库提供的快速排序函数,通过传入比较函数,实现对结构体数组按 pages
成员升序排序。
代码
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// 定义结构体
struct book {
char title[50];
char author[30];
int pages;
};
// 比较函数,用于qsort
int compare(const void *a, const void *b) {
struct book *book1 = (struct book *)a;
struct book *book2 = (struct book *)b;
return (book1->pages - book2->pages);
}
int main() {
struct book books[10] = {
{"Book1", "Author1", 200},
{"Book2", "Author2", 150},
{"Book3", "Author3", 250},
{"Book4", "Author4", 180},
{"Book5", "Author5", 300},
{"Book6", "Author6", 120},
{"Book7", "Author7", 220},
{"Book8", "Author8", 160},
{"Book9", "Author9", 280},
{"Book10", "Author10", 140}
};
// 使用qsort进行排序
qsort(books, 10, sizeof(struct book), compare);
// 输出排序后的结果
for (int i = 0; i < 10; i++) {
printf("Title: %s, Author: %s, Pages: %d\n", books[i].title, books[i].author, books[i].pages);
}
return 0;
}