使用sort()函数进行排序(C++)

1. 使用sort函数进行默认的从小到大排序

#include <iostream>
#include <cstring>
#include <algorithm>

using namespace std;

///函数形式:sort(首元素地址,尾元素地址的下一个地址,比较函数(非必填))
///不写比较函数默认进行递增排序

int main()
{
    //1. 对int型数组排序
    int a[]={4,8,6,2,3,9};
    for(int i=0;i<6;i++)    //输出原本顺序
        cout<<a[i]<<" ";
    cout<<endl;

    sort(a,a+5);            //对a[0]~a[4]进行排序
    for(int i=0;i<6;i++)
        cout<<a[i]<<" ";
    cout<<endl;

    //2. 对浮点数数组排序
    float b[]={9.1,3.33,-0.2};
    sort(b,b+3);
    for(int i=0;i<3;i++)
        cout<<b[i]<<" ";
    cout<<endl;

    //3. 对字符型数组排序(默认字典序)
    char c[]={'f','a','r','g'};
    sort(c,c+4);
    for(int i=0;i<4;i++)
        cout<<c[i]<<" ";
    cout<<endl;

    return 0;
}

 

2. 使用sort函数进行从大到小排序

#include <iostream>
#include <cstring>
#include <algorithm>

using namespace std;

///函数形式:sort(首元素地址,尾元素地址的下一个地址,比较函数(非必填))
///不写比较函数默认进行递增排序

bool cmp(int a,int b)
{
    return a>b;
}

int main()
{
    //4. 使用cmp()比较函数进行自定义规则排序
    //(1)对int型进行从大到小排序
    int A[]={4,7,6,9,2,-1};
    sort(A,A+6,cmp);
    for(int i=0;i<6;i++)
        cout<<A[i]<<" ";
    cout<<endl;

    return 0;
}

 

3. 使用sort函数对结构体数组进行自定义排序

#include <iostream>
#include <cstring>
#include <algorithm>

using namespace std;

///函数形式:sort(首元素地址,尾元素地址的下一个地址,比较函数(非必填))
///不写比较函数默认进行递增排序

struct Node
{
    int x,y;
}nodes[3];

bool cmp(Node a,Node b)
{
    return a.x>b.x;
}


int main()
{
    //(2)对结构体数组进行排序
    //Node nodes[3];
    nodes[0].x=2;    //(2,2)
    nodes[0].y=2;
    nodes[1].x=3;    //(3,5)
    nodes[1].y=5;
    nodes[2].x=1;    //(1,3)
    nodes[2].y=3;
    sort(nodes,nodes+3,cmp);   //按x从大到小排序
    for(int i=0;i<3;i++)
        cout<<"("<<nodes[i].x<<","<<nodes[i].y<<")  ";
    cout<<endl;

    return 0;
}

 

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

音无八重

谢谢老板!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值