qsort与sort
来源:互联网 发布:安徽八度网络 编辑:程序博客网 时间:2024/06/03 11:19
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);
- sort与qsort函数
- sort与qsort
- qsort与sort
- qsort与sort
- qsort与sort
- sort与qsort
- sort()与qsort()
- sort 与 qsort
- std::sort与qsort
- qsort与sort 排序
- sort与qsort函数
- qsort与sort
- sort 与Qsort 排序
- qsort与sort
- sort与qsort
- sort与qsort
- sort 与 qsort
- 排序sort与qsort
- 带头结点的双向循环链表的表示和实现
- UVA 10815(字符串)
- static、final修饰符、内部类
- 2.5 创建主角;2.5.1 创建脚本
- HDJ2020绝对值排序
- qsort与sort
- www外部加载
- 简历相关问题
- 绝对值排序
- GTK中在scrolled_window区域用滑轮操作独立scrollbar的方法
- 杭电1003
- 代代星笔试题
- O_RDWR, O_CREAT等open函数标志位在哪里定义?
- 工作日记-华为iscsi排查