sort函数对数组排序

来源:互联网 发布:unity3d 3dmax 编辑:程序博客网 时间:2024/05/16 07:12

注意

头文件:

#include <algorithm>

using namespace std;
1.默认的sort函数是按升序排。对应于1)sort(a,a+n);   //两个参数分别为待排序数组的首地址和尾地址
2.可以自己写一个cmp函数,按特定意图进行排序。对应于2)例如: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升序排

典型代码:

//简版#include <algorithm>using namespace std;   sort(a,a+20);///#include <algorithm>using namespace std;bool compare(int a,int b){    return a<b;   //升序排列,如果改为return a>b,则为降序}int main(){    int a[20]={2,4,1,23,5,76,0,43,24,65},i;    for(i=0;i<20;i++)        printf("%d ",a[i]);    printf("\n");        sort(a,a+20,compare);        for(i=0;i<20;i++)        printf("%d ",a[i]);    printf("\n");        return 0;}


	
				
		
原创粉丝点击