函数库的排序调用 sort qsort

两个都在C++函数库里面

#include <algorithm>
using namespace std;


sort(a,a+n,cmp);cmp可加可不对 对数列从某位置到某位置进行排序

如果不加cmp则按小到大排 cmp是排序的条件


bool cmp(int x,int y)
return x>y; 

这里就按大到小排 传入的类型可以是各种类型 跟A数组一致即可

qsort(a,n,sizeof(int),cmp);  用法有点不一样 必须有4个参数 首位置 到哪个位置 大小 条件

int comp(const void*a,const void*b)
{
return *(int*)a-*(int*)b;
}
</pre><pre name="code" class="cpp"><pre name="code" class="cpp">int a[1000][2];
//其中按照a[0]的大小进行一个整体的排序,其中a[1]必须和a[0]一起移动交换。
//使用库函数排序的代码量并不比用冒泡排序法小,但速度却快很多。
qsort(a,1000,sizeof(int)*2,comp);

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

{
	return((int*)a)[0]-((int*)b)[0];
}

//按结构体中某个关键字排序(对结构体一级排序):
structNode
{
	double data;
	int other;
}s[100];
int Comp(const void *p1,const void *p2)
{
	return(*(Node*)p2).data>(*(Node*)p1).data?1:-1;
}
//按结构体中多个关键字排序(对结构体多级排序)[以二级为例]:
struct Node
{
	int x;
	int y;
}s[100];
//按照x从小到大排序,当x相等时按y从大到小排序
int Comp(const void*p1,const void*p2)
{
	struct Node*c=(Node*)p1;
	struct Node*d=(Node*)p2;
	if(c->x!=d->x)returnc->x-d->x;
	else return d->y-c->y;
}
//对结构体中字符串进行排序:
struct Node
{
	int data;
	char str[100];
}s[100];
//按照结构体中字符串str的字典序排序
int Comp(const void*p1,const void*p2)
{
	return strcmp((*(Node*)p1).str,(*(Node*)p2).str);
}
</pre><pre name="code" class="cpp"><pre name="code" class="cpp">一、对int类型数组排序

int cmp ( const void *a , const void *b )
{
	return *(int *)a - *(int *)b;
}

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

int cmp( const void *a , const void *b )
{
	return *(char *)a - *(char *)b;
}


三、对double类型数组排序(特别要注意)

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

 
 


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值