c语言qsort详解

博客主要介绍C语言常用库函数,重点提及了qsort函数。qsort在C语言编程中较为常用,能帮助开发者更高效地进行排序等操作,属于信息技术领域中C语言编程的相关内容。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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)返回值描述
<0elem1被排在elem2前面
=0注意!快排是不稳定排序。这个无法判断
>0elem1被排在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;
} 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值