先来看一下qsort函数的介绍:
Compare 函数的返回值 | 描述 |
>0 | elem1将被排在elem2前面 |
0 | elem1等于elem2 |
<0 | elem1 将被排在elem2后面 |
参数
- base-- 指向要排序的数组的第一个元素的指针。
- nitems-- 由 base 指向的数组中元素的个数。
- size-- 数组中每个元素的大小,以字节为单位。
- compar-- 用来比较两个元素的函数,即函数指针(回调函数)
compar参数
compar参数指向一个比较两个元素的函数。比较函数的原型应该像下面这样。注意两个形参必须是const void
*型,同时在调用compar 函数(compar实质为函数指针,这里称它所指向的函数也为compar)时,传入的实参也必须转换成const void *型。在compar函数内部会将const void *型转换成实际类型。
排序整型数组
```c #include <stdio.h> #include <stdlib.h> int cmp_int(const void* num1,const void* num2) { int* pa = (int*)num1; int* pb = (int*)num2; return *pa - *pb; } int main() { int arr[5] = { 2,3,1,6,5 }; qsort(arr, 5, sizeof(arr[0]), cmp_int); int i = 0; for (i = 0; i < 5; i++) { printf("%d ", arr[i]); } return 0; }
想要从大到小的话,把return *pa - *pb;倒过来即可,即return *pb - *pa;。
排序浮点型数组
int cmp_int(const void* num1, const void* num2) { float* pa = (float*)num1; float* pb = (float*)num2; return *pa > *pb ? 1 : -1; } int main() { float arr[6] = { 2,3,1,6,5,5 }; qsort(arr, 6, sizeof(float), cmp_int); int i = 0; for (i = 0; i < 6; i++) { printf("%f ", arr[i]); } return 0; }
排序结构体
//按语文成绩排序 typedef struct { char name[10]; int Chinese; int Math; int English; }Student; Student students[7]; void readData()//读入学生数据 { FILE* file = fopen("mark.txt", "r"); int i = 0; for (i = 0; i < 7; i++) { fscanf(file, "%s", students[i].name); fscanf(file, "%d", &students[i].Chinese); fscanf(file, "%d", &students[i].Math); fscanf(file, "%d", &students[i].English); } fclose(file); file = NULL; } void DisPlayData() { int i = 0; for (i = 0; i < 7; i++) { printf("%s\t", students[i].name); printf("%d\t", students[i].Chinese); printf("%d\t", students[i].Math); printf("%d\n", students[i].English); } } int cmp(const void* num1, const void* num2) { Student* pa = (Student*)num1; Student* pb = (Student*)num2; int num3 = pa->Chinese; int num4 = pb->Chinese; return num3 - num4; } int main() { readData(); qsort(students, 7, sizeof(Student), cmp); DisPlayData(); return 0; }
按总分数排序
typedef struct { char name[10]; int Chinese; int Math; int English; }Student; Student students[7]; void readData()//读入学生数据 { FILE* file = fopen("mark.txt", "r"); int i = 0; for (i = 0; i < 7; i++) { fscanf(file, "%s", students[i].name); fscanf(file, "%d", &students[i].Chinese); fscanf(file, "%d", &students[i].Math); fscanf(file, "%d", &students[i].English); } fclose(file); file = NULL; } void DisPlayData() { int i = 0; for (i = 0; i < 7; i++) { printf("%s\t", students[i].name); printf("%d\t", students[i].Chinese); printf("%d\t", students[i].Math); printf("%d\t", students[i].English); printf("%d\n", students[i].Chinese + students[i].Math + students[i].English); } } int cmp(const void* a, const void* b) { Student* pa = (Student*)a; Student* pb = (Student*)b; int num3 = pa->Chinese+pa->English+pa->Math; int num4 = pb->Chinese+pb->Chinese+pb->Math; return num3 - num4; } int main() { readData(); qsort(students, 7, sizeof(Student), cmp); DisPlayData(); return 0; }