qsort()排序函数

 

qsort()排序函数

排序是最常用的预处理技术

qsort包含在<stdlib.h>头文件中

函数根据你给的比较条件进行快速排序

排序之后的结果仍然放在原数组中

使用qsort函数必须自己写一个比较函数。

一、对整型数组排序

Int main()

{

  int a[10]={4,2,7,3,6,1,5};

  int i,n=7;

  qsort(a, n,sizeof(a[0]),cmp);

  for(i=0;i<n;i++)

      printf(“%d “,a[i]);

}

int cmp ( const void *a , const void *b )
{
int *c=(int *)a; //(int*)是强制类型转换

Int *d=(int *)b;

return *c-*d;

}

等同于return *(int *)a - *(int *)b;

二、对char类型数组排序(同int类型)

Int main()

{

  char str[10]=“gjlfjsder”;

  int i,n;

  n=strlen(str);

  qsort(a, n,sizeof(a[0]),cmp);

  puts(str);

}

int cmp ( const void *a , const void *b )
{
char *c=(char *)a; //(char*)是强制类型转换

char *d=(char *)b;

return *c-*b;

}

 

等同于return *(char *)a - *(char *)b;

三、对double类型数组排序(同int类型)

Int main()

{

  double a[10]={5, 2.5, 1.3, 3.2};

  int i,n=4;

  qsort(a, n,sizeof(a[0]),cmp);

  for(i=0;i<n;i++)

        printf(“%.2f “,a[i]);}

int cmp ( const void *a , const void *b )
{
double *c,*d;

c=(double *)a;

d=(double *)b;

return *c>*d ? 1 : -1; //不是return *c-*d

}

等同于return *(double*)a > *(double *)b ? 1:-1;

四、对结构体数组一级排序

struct student
{
char name[10];
int score;
}stu[100];

int cmp( const void *a ,const void *b)

{
struct student *c, *d;

c=(struct student *)a;

d=(struct student *)b;

return  d->score – c->score;   //降序

}

调用:qsort(stu, 100, sizeof(stu[0]),cmp)

五、对结构体数组二级排序

按照成绩的值从大到小排序,

成绩相同者按姓名从小到大排序

struct student
{
char name[10];
int score;
}stu[100];

int cmp( const void *a ,const void *b)

{
struct student *c, *d;

c=(struct student *)a;

d=(struct student *)b;

if(d->score!=c->score)

   return  d->score – c->score;   //降序

else  //成绩相同,按姓名升序

   return strcmp(c->name, d->name);//字符串排序

}

调用:qsort(stu, 100, sizeof(stu[0]),cmp)

 
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值