c++常用函数之sort函数

概述

排序有很多种,希尔,归并,桶,堆……每个用途都不太一样,比如归并的找逆序对啥的,每种排序的时间复杂度都不一样,但是c++封装了一个sort函数,可以给数组进行排序。sort的时间复杂度类似于快排是nlongn的(据说进行了优化)。

sort的头文件

#include<algorithm>
//用万能头也不是不行
using namespace std;
//如果不用这个的话,在sort前面得加上std::

sort的参数

sort有三个参数
1.排序数组起始地址
2.排序数组结尾地址的后一个地址(简单来说就是左开右闭)
3。第三个参数是排序的方法,可以是从大到小也可是从小到大,还可以不写第三个参数,此时默认的排序方法是从小到大排序。

范例

#include <bits/stdc++.h>
using namespace std;
int main()
{
    int a[] = {1, 3, 4, 5, 2};
    sort(a, a + 5);//默认升序
    for (int i = 0; i < 5; i++)
        cout << a[i] << " ";
    cout << endl;
}

在这里插入图片描述
当然我们可以用greater进行降序排序

#include <bits/stdc++.h>
using namespace std;
int main()
{
    int a[] = {1, 3, 4, 5, 2};
    sort(a, a + 5 , greater<int>());//<>里的是数组的类型
    for (int i = 0; i < 5; i++)
        cout << a[i] << " ";
    cout << endl;
}

在这里插入图片描述

自定义排序

我们也可以自定义排序,就是定义一个函数来进行,按照函数所提供的规则进行排序

范例1

#include <bits/stdc++.h>
using namespace std;
bool cmp(int x, int y)
{
    return x > y; // 返回1就是要进行交换顺序
}
int main()
{
    int a[] = {1, 3, 4, 5, 2};
    sort(a, a + 5, cmp);
    for (int i = 0; i < 5; i++)
        cout << a[i] << " ";
    cout << endl;
}

在这里插入图片描述

我们也可以自定义结构体进行排序
结构体排序分两种
1.写一个结构体,加一个排序函数进行排序
2.写一个结构体,重载比较操作来进行排序(看不懂的话看下面代码)

范例2

//第一种
#include <bits/stdc++.h>
using namespace std;
struct node
{
    int x, y;
} a[10];

bool cmp(node x, node y)
{
    return x.x > y.x;
}
int main()
{
    a[1].x = a[1].y = 1;
    a[2].x = a[2].y = 3;
    a[3].x = a[3].y = 2;
    a[4].x = a[4].y = 5;
    a[5].x = a[5].y = 4;
    sort(a + 1, a + 1 + 5, cmp);
    for (int i = 1; i <= 5; i++)
        cout << a[i].x << " " << a[i].y << endl;
}

在这里插入图片描述

 //第二种
 #include <bits/stdc++.h>
using namespace std;
struct node
{
    int x, y;
    friend bool operator < (node a,node b)
    {
        //效果就相当于node这个类型可以进行比较 返回1就是a.x小于b.x
        return a.x < b.x;
    }
} a[10];

int main()
{
    a[1].x = a[1].y = 1;
    a[2].x = a[2].y = 3;
    a[3].x = a[3].y = 2;
    a[4].x = a[4].y = 5;
    a[5].x = a[5].y = 4;
    sort(a + 1, a + 1 + 5);
    for (int i = 1; i <= 5; i++)
        cout << a[i].x << " " << a[i].y << endl;
}

在这里插入图片描述

  • 5
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值