qsort与sort

 sort()函数是C++中的排序函数其头文件为:#include<algorithm>头文件;

 qsort()是C中的排序函数,其头文件为:#include<stdlib.h>

sort是不需要自己写compare的,sort默认是升序排列,如果想要降序就需要写一个compare。

#include<iostream>

#include<algorithm>

using namespace std;//sort用在c++,需要加上这个用语

int cmp(int a,int b)

{

 if(a<b)

 return 1; //升序排列,如果改为 a >b,则为降序,要注意sort()中cmp()的返值只有1和0,不像qsort中存在-1!!!!

 else

 return 0;

}

 

int main(){

       inti;

 inta[20];

 for(int i=0;i<5;++i)

 cin>>a[i];

sort(a,a+5,cmp);           //范围,很明显这里是a+5 注意,这是必要的,如果是a+4最后一个值a[4]就不会参与排序。

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

cout<<a[i]<<endl;

       system("pause");

/*system("pause")就是从程序里调用“pause”命令;   
  而“pause”这个系统命令的功能很简单,就是在命令行上输出一行类似于“Press   any   key   to   exit”的字,等待用户按一个键,然后返回。*/

 return 0;

}

qsort :

参数:

 1 待排序 数组首地址
2 数组中待排序元素数量
3 各元素的占用空间大小
4 指向函数的 指针,用于确定排序的顺序

double类型

double in[100];

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

qsort(in,100,sizeof(in[0]),cmp);

一级排序:

intcomp( const  void *a, const  void *b)
{
return  *( int *)a-*( int *)b;升序
}

*( int *)b-*( int *)a;降序



二级排序:

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

{

struct In *c = (In *)a;

struct In *d = (In *)b;

if(c->x != d->x) return c->x -d->x;

else return d->y - c->y;

}

qsort(s,100,sizeof(s[0]),cmp);


三级排序:

int cmp(const void *a,const void *b)
{
struct node *c=(node *)a;
struct node *d=(node *)b;
if(c->no==d->no)
{
if(c->l==d->l)
{
return c->w-d->w;
}
else return c->l-d->l;
}
else return c->no-d->no;
}

qsort(a,m,sizeof(node),cmp);


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

樱缘之梦

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值