• C++中的sort()函数


    C++中的sort()函数

     

    1.  sort()函数是C++中的排序方法之一,时间复杂度为 n*log2n,执行效率较高

    2.  使用sort()函数的头文件:#include<algorithm>

    3.  sort()函数的三个参数:

    sort(start,end,compare)

    ①start:要排序数组的起始地址

    ②end:要排序数组的结束地址(要排序数组的最后一个元素的下一个地址)

    ③compare:比较方法,从小到大或者是从大到小,第三个参数可以不写,默认是从小到大排序

    4.用sort()方法实现数的排序

    实例代码:

    #include<iostream>
    #include<algorithm>
    using namespace std;
    bool compare(int a,int b)//比较函数,使排序从大到小 
    {
    	return a>b;
    }
    int main()
    {
    	int a[5];
    	for(int i=0;i<5;i++)
    	{
    		cin>>a[i];
    	}
    	sort(a,a+5);//从小到大排序 
    	for(int i=0;i<5;i++)
    	{
    		cout<<a[i]<<" ";
    	}
    	cout<<endl;
    	sort(a,a+5,compare);//从大到小排序,在这里就不需要对complare函数传入参数 
    	for(int i=0;i<5;i++)
    	{
    		cout<<a[i]<<" ";
    	}
    	return 0;
    }
    

      

    运行结果:

    5.  用sort()方法实现string内的字符按照abcd。。。。排序

    实例代码:

    #include<iostream>
    #include<algorithm>
    #include<cstring>
    using namespace std;
    bool cmp(char a,char b)//比较函数
    {
        return a>b;
    }
    int main()
    {
        string s;
        cin>>s;
        sort(s.begin(),s.end());//从小到大
        cout<<s<<endl;
        sort(s.begin(),s.end(),cmp);//从大到小
        cout<<s<<endl;
        cout<<s.length()<<endl;//字符串长度函数
    }
    

     

    运行结果:

     

    6.  用sort()方法实现对一维数组内的字符进行排序

    实例代码:

    #include<cstdio>
    #include<iostream>
    #include<cstring>
    #include<algorithm>
    using namespace std;
    bool cmp(char a,char b)//比较函数
    {
        return a>b;
    }
    int main()
    {
        char a[100];
        scanf("%s",a);
        sort(a,a+strlen(a));//从小到大
        cout<<a<<endl;
        sort(a,a+strlen(a),cmp);//从大到小
        cout<<a<<endl;
        cout<<strlen(a)<<endl;//输出字符数组a的长度
     
    }
    

    运行结果:

  • 相关阅读:
    Codeforces 67A【模拟】
    Codeforces325 D【并查集维护连通性】
    CodeForces 363D 【二分+贪心】
    Lightoj1084【DP啊DP】
    lightoj1062【几何(二分)】
    lightoj1066【BFS】
    lightoj1064 【DP求方案】
    lightoj1063【求割点】
    lightoj 1074【spfa判负环】
    CodeForces 382C【模拟】
  • 原文地址:https://www.cnblogs.com/canneddream/p/14169671.html
Copyright © 2020-2023  润新知