void qsort(void * base,size_t nmemb,size_t size ,int(*compar)(const void *,const void *));
要传参数分别是:
要排序的首字母地址,需要排序的个数,每个数个大小,指向函数的指针(用来确定升序还是降序)
如:
int型:
int common(const void *a,const void *b)//升序
{
return *(int *)a-*(int *)b;
}
int common(const void *a,const void *b)//降序
{
return *(int *)b-*(int *)a;
}
字符串:
int common(const void *a, const void *b)
{
return * (char *)a - *(char * )b;
}
根据字符串长度排序
int common(const void *a, const void *b)
{
return strlen((char * )a) > strlen((char * )b) ? 1 : -1;
}
如果是结构图需要排序可很容易:
附上牛客网一道题:
答案如下:
#include<stdio.h>
#include<stdlib.h>
#define maxsize 100
struct student
{
char name[maxsize];
int score;
};
int common(const void *a,const void *b)//升序
{
return ((student*)a)->score - ((student*)b)->score;
}
int commonde(const void *a,const void *b)//降序
{
return ((student*)b)->score - ((student*)a)->score;
}
int main()
{
while(true)//牛客网测试用例 的问题,不单纯测试可忽略;
{
int n=0;//有几个学生
int m=0;//m为1位需要降序,m为0为需要升序;
scanf("%d",&n);
getchar();
scanf("%d",&m);
getchar();
if(n<=0||m>1||m<0)
return 0;
student stu[n];
for(int i=0; i<n; i++)
{
int j=0;
for(int j=0; j<maxsize; j++)
{
scanf("%c",&stu[i].name[j]);
if(stu[i].name[j]==' ')
break;
}
scanf("%d",&stu[i].score);
getchar();
}
if(m)
{
qsort(stu,n,sizeof(stu[0]),common);
}
else
{
qsort(stu,n,sizeof(stu[0]),commonde);
}
for(int i=0; i<n; i++)
{
int j=0;
for(int j=0; j<maxsize; j++)
{
printf("%c",stu[i].name[j]);
if(stu[i].name[j]==' ')
{
break;
}
}
printf("%d\n",stu[i].score);
}
}
return 0 ;
}
如果结构图需要二级排序:
int common( const void *a , const void *b )
{
if((* (node * )a).one != ( * (node * )b).one)
return ( * (node * )a).one > ( * (node * )b).one ? 1 : -1;
else
return (* (node * )a).two -( * (node * )b).two;
}