自定义sort函数排序

int a[10];  

1、sort函数的时间复杂度为n*log2(n),执行效率较高。

2、sort函数的形式为sort(a+i,a+j,自定义排序规则名)//其中第三个参数可不填。其排序区间为[i,j);

3、若为两个参数,则sort的排序默认是从小到大。

例:

1、bool cmp(int a,int b)//int 可改为其他类型,如double........

     {

        return a>b;//定义一整型数组,按从大到小的顺序排列;无'='号,遇到相同的两个数不排序;

      }

int main()

{

 int a[10]={0,1,5,9,6,3,8,2,9,2};

sort(a,a+10,cmp);//输出结果//9,9,8,6,5,3,2,2,1,0,

}

2、bool cmp(struct a,struct b)//在定义结构体时必须要有结构体名,或用typedef定义

    {

      return a.data>b.data;//结构体按data从大到小排序;

    }

#include<iostream>
#include<algorithm>
using namespace std;


typedef struct

{
    int grade;
    string name;
}stu;

bool cmp(stu a,stu b)//类型名可任意取
{
    return a.grade>b.grade;//自定义按照grade从大到小排序,无'='号,遇到相同的grade不排序;
}

int main()
{
    stu student[5];

    for(int i=0;i<5;i++)
        cin>>student[i].name>>student[i].grade;
    sort(student,student+5,cmp);//多了一个cmp成员
    for(int i=0;i<5;i++)
        cout<<student[i].name<<' '<<student[i].grade<<endl;
    return 0;
}



猜你喜欢

转载自blog.csdn.net/violet_ljp/article/details/79936612