#include<stdlib.h>
注意:qsort不稳定 如题目要求相同按照原顺序排序,如果要用qsort,就用结构体设置优先级,二级排序比较。但建议还是手写排序算法。
qsort(数组名, 元素个数, 数组元素所占字节sizeof(int), cmp);
目录
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);
}