qsort() && sort() 排序函数

#include<stdio.h>
#include<string.h>
#include<stdlib.h>

int s[100], n, i;

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

int main()
{
	scanf("%d", &n);
	for (i = 0; i < n; i++)
		scanf("%d", &s[i]);
	qsort(s, n, sizeof(s[0]), cmp);
	for (i = 0; i < n; i++)
		printf("%d  ", s[i]);

	system("pause");
	return 0;
}


#include<stdio.h>
#include<string.h>
#include<stdlib.h>

char w[100];

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

int main()
{
	int n, i;
	
	scanf("%d", &n);
	for (i = 0; i < n; i++)
		scanf("%c", &w[i]);
	qsort(w, n, sizeof(w[0]), cmp);
	for (i = 0; i < n; i++)
		printf("%c ", w[i]);

	system("pause");
	return 0;
}




头文件:
#include <algorithm>
using namespace std;

1.默认的sort函数是按升序排。
sort(a,a+n); //两个参数分别为待排序数组的首地址和尾地址


2.可以自己写一个cmp函数,按特定意图进行排序。
例如:
int cmp( const int &a, const int &b ){
if( a > b )
return 1;
else
return 0;
}
sort(a,a+n,cmp);
是对数组a降序排序


又如:
int cmp( const POINT &a, const POINT &b ){
if( a.x < b.x )
return 1;
else
if( a.x == b.x ){
if( a.y < b.y )
return 1;
else
return 0;
}
else
return 0;
}
sort(a,a+n,cmp);
是先按x升序排序,若x值相等则按y升序排




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值