概述
使用C语言,实现结构体多元素,排序算法(冒泡排序),这里使用示例:书籍示例讲解
函数简介
函数声明
void qsort(void *base, size_t nitems, size_t size, int (*compar)(const void *, const void*))
参数
base-- 指向要排序的数组的第一个元素的指针。
nitems-- 由 base 指向的数组中元素的个数。
size-- 数组中每个元素的大小,以字节为单位。
compar-- 用来比较两个元素的函数,即函数指针(回调函数)
编码环境:Visual Studio 2022
1、code
#include "stdio.h"
#include <iostream>
using namespace std;typedef struct BooksInfo_t {char name[20]; //书名char date[15]; //出版日期int number; //编号double price; //价格
}BooksInfo;#define ARRAYSIZE(x) sizeof(x) / sizeof(x[0])int Cmp_name(const void* o1, const void* o2) {//指针类型为qsort第一个参数的类型return strcmp(((BooksInfo*)o1)->name, ((BooksInfo*)o2)->name);
}int Cmp_date(const void* o1, const void* o2) {return strcmp(((BooksInfo*)o1)->date, ((BooksInfo*)o2)->date);
}int Cmp_number(const void* o1, const void* o2) {return ((BooksInfo*)o1)->number - ((BooksInfo*)o2)->number;
}int Cmp_price(const void* o1, const void* o2) {double tmp = ((BooksInfo*)o1)->price - ((BooksInfo*)o2)->price;if (tmp > 0)return 1;else if (tmp == 0)return 0;else if (tmp < 0)return -1;
}void Show(BooksInfo* info, int len)
{for (int i = 0; i < len; i++){printf("%s, %s, %d, %lf\n", info[i].name, info[i].date, info[i].number, info[i].price);}
}int main(void)
{//初始化书籍结构体BooksInfo book[] = {"C ", "2022.1.23", 20, 85.5,"C++ ", "2023.4.28", 19, 96.5,"Java ", "2000.8.09", 5, 102.5,"Python", "2019.3.02", 92, 65.8,"C# ", "2024.12.5", 7, 155.9};//按书名排序qsort(book, ARRAYSIZE(book), sizeof(book[0]), Cmp_name);printf("按书名排序:\n");Show(book, ARRAYSIZE(book));//按出版日期排序qsort(book, ARRAYSIZE(book), sizeof(book[0]), Cmp_date);printf("按出版日期排序:\n");Show(book, ARRAYSIZE(book));//按编号排序printf("按编号排序:\n");qsort(book, ARRAYSIZE(book), sizeof(book[0]), Cmp_number);Show(book, ARRAYSIZE(book));//按价格排序qsort(book, ARRAYSIZE(book), sizeof(book[0]), Cmp_price);printf("按价格排序:\n");Show(book, ARRAYSIZE(book));return 0;
}
2、运行结果
3、总结
希望能帮助到需要的人,加油,噢力给 ^_^!!!