qsort汇总

#include<stdlib.h>

注意:qsort不稳定 如题目要求相同按照原顺序排序,如果要用qsort,就用结构体设置优先级,二级排序比较。但建议还是手写排序算法。 

qsort(数组名, 元素个数, 数组元素所占字节sizeof(int), cmp);

目录

1.整型(int)

2.浮点数(double)

3.字符(char)

 4.字符串长度比较

5.结构体


 

1.整型(int)

int cmp(const void *a,const void *b){
	return *(int*)a-*(int*)b; 
} 

2.浮点数(double)

浮点数会存在精度损失的问题,需要通过比较来返回1或-1,以确定是增序还是降序。

int cmp(const void *a,const void *b){
	return *(double*)a>*(double*)b?1:-1; 
} 

3.字符(char)

int cmp(const void *a,const void *b){
	return *(char*)a-*(char*)b; 
} 

 4.字符串长度比较

int cmp(const void*a,const void*b){
	return strlen((char *)a)-strlen((const char*)b);
}
qsort(ans,5,sizeof(ans[0]),cmp);

5.结构体

struct friends{
	char name[12];
	char birthday[10];
	char number[20];
};
int cmp(const void *p1, const void *p2) {
    return strcmp(((struct friends*)p1)->birthday, ((struct friends*)p2)->birthday);
}

二级:

struct student{
	int xh;
	int score;
};
int cmp(const void *a,const void *b){
	if(((struct student*)a)->score==((struct student*)b)->score)
		return ((struct student*)a)->xh-((struct student*)b)->xh;
	else
		return ((struct student*)a)->score-((struct student*)b)->score;
}



	qsort(stu,n,sizeof(stu[0]),cmp); 
struct student{
	char name[50];
	int score;
	int order;
};
int flag;
int cmp(const void *a,const void *b){
	struct student *s1=(struct student*)a;
	struct student *s2=(struct student*)b;
	if(s1->score==s2->score)
		return s1->order-s2->order;
	return flag==1?(s1->score-s2->score):(s2->score-s1->score);
}

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值