c语言常用库函数
qsort简介
//首先,请include<stdlib.h>
//函数原型
void qort(void *base,int nelem,int width,int (*fcmp)(const void*,const void*));
//各参数解释
/**
* 1:待排序数组首地址,2:数组中待排序元素个数,3:每个元素占用空间大小,4:比较大小函数指针(用于确定排
* 序的顺序)
*/
//最后一个决定排序结果的函数指针是关键
cmp函数(const void* elem1,const void*elem2)返回值 | 描述 |
---|---|
<0 | elem1被排在elem2前面 |
=0 | 注意!快排是不稳定排序。这个无法判断 |
>0 | elem1被排在elem2后面 |
//代码示意
//Sample 1 int类型排序
int cmp(const void* a, const void* b){
return *(int*)a - *(int*)b;
}
/*
* 注意点1:首先不要忘了 类型转换,因为一开始你传进来的参数类型是 void*
* 注意点2:注意返回值应为int
*/
//Sample 2 double等浮点数类型排序
int cmp(const void* a, const void* b){
return *(double*)a > *(double*)b ? 1:-1;
}
/*
* 您可一定要注意 与上面int写法的不同哟~
* 返回值的问题,显然cmp返回的是一个整型,所以避免double返回小数而被丢失,用一个判断返回值。
*/
//Sample 3 一级结构排序
struct Student{
int stuID;
int score;
}stu[100];
int cmp(const void* a, const void* b){
struct Student * stua = (struct Student *) a;
struct Student * stub = (struct Student *) b;
return stua->stuID - stub->stuID;
}
//借助stuId 实现学号递减顺序排序
//Sample 4 二级结构排序,咳咳,敲黑板了,注意!
struct Student { // 定义结构体Student,stuID表示学号, score表示分数
int stuID;
int score;
};
int cmp(const void* a, const void* b){
struct Student * stua = (struct Student *) a;
struct Student * stub = (struct Student *) b;
if(stua->score != stub->score){
return stub->score - stua->score; // 如果学生分数不同,就按照分数从大到小排列
}
else{ // 如果学生分数相同,就按照学号从小到大排列
return stua->stuID > stub->stuID ? 1:-1;
}
}
// 有时候这种简单的if-else语句我喜欢直接⽤⼀个C语⾔⾥⾯的三⽬运算符表示~
int cmp(const void* a, const void* b) {
struct Student * stua = (struct Student *) a;
struct Student * stub = (struct Student *) b;
return stua->score != stub->score ? stub->score - stua->score : stua->stuID - stub- >stuID;
}