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 :
参数:
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);