做一个网站需要多少时间,网站制作厂家电话多少,外贸网站建设科技,微信app下载安装旧版本sort()函数是C中的排序函数其头文件为#xff1a;#includealgorithm头文件#xff1b; qsort()是C中的排序函数#xff0c;其头文件为#xff1a;#includestdlib.h
sort是不需要自己写compare的#xff0c;sort默认是升序排列#xff0c;如果想要降序就… sort()函数是C中的排序函数其头文件为#includealgorithm头文件 qsort()是C中的排序函数其头文件为#includestdlib.h
sort是不需要自己写compare的sort默认是升序排列如果想要降序就需要写一个compare。 #includeiostream
#includealgorithm
using namespace std;//sort用在c需要加上这个用语
int cmp(int a,int b)
{ if(ab) return 1; //升序排列如果改为 a b则为降序,要注意sort()中cmp()的返值只有1和0不像qsort中存在1 else return 0;
} int main(){ inti; inta[20]; for(int i0;i5;i) cina[i];
sort(a,a5,cmp); //范围很明显这里是a5 注意这是必要的如果是a4最后一个值a[4]就不会参与排序。
for(i0;i5;i)
couta[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-nod-no) { if(c-ld-l) { return c-w-d-w; } else return c-l-d-l; } else return c-no-d-no; }
qsort(a,m,sizeof(node),cmp);