C++中sort排序函数

功能:

sort是用来排序的函数,根据具体情形使用不同的排序方法,效率较高,时间复杂度O(nlogn)。std::sort 是 C++ 标准库中的一个通用排序函数,它用于将给定范围内的元素按照指定的顺序进行排序。 

头文件:

使用sort函数需要包含其对应头文件<algorithm> 头文件

#include <algorithm>

使用方法:

sort(首元素地址(必填),尾元素地址的下一个地址(必填),比较函数(非必填));

一般有升序排列和降序排列可选择,默认为升序排列。

升序排列:

#include <iostream>
#include <algorithm>
#include <vector>

using namespace std;

int main() {
    //方式一:数组
    int a[10] = {3,2,1,6,5,4,9,8,7,0}; //数组名即为数组首元素地址
    sort(a, a + 10);  // 10为元素个数(排10个)
    for(int i = 0; i < 10; ++i) 
        cout << a[i] << ' ';    
    //排序后数组0,1,2,3,4,5,6,7,8,9
    cout << endl;

    //方式二:vector容器
    vector<int> arr = {3,2,1,6,5,4,9,8,7,0};
    sort(arr.begin(), arr.end());  // 10为元素个数
    for(int i = 0; i < 10; ++i) 
        cout << arr[i] << ' ';
    //排序后数组0,1,2,3,4,5,6,7,8,9
    cout << endl;

    return 0;
}

降序排列:

法一:

传入第三个参数–比较函数greater<type>(),这里的元素为int 类型,即函数为greater<int>(); 如果是其他基本数据类型如floatdoublelong等同理。

#include <iostream>
#include <algorithm>
#include <vector>

using namespace std;

int main() {
    // 方式一:数组
    int a[10] = {3,2,1,6,5,4,9,8,7,0};
    sort(a, a + 10, greater<int>());  
    for (int i = 0; i < 10; ++i) 
        cout << a[i] << ' ';		
    //排序后数组9 8 7 6 5 4 3 2 1 0
    cout << endl;	

    // 方式二:vector容器
    vector<int> arr = {3,2,1,6,5,4,9,8,7,0};
    sort(arr.begin(), arr.end(), greater<int>()); 
    for (int i = 0; i < 10; ++i) 
        cout << arr[i] << ' ';
    cout << endl;
    //排序后数组9 8 7 6 5 4 3 2 1 0

    return 0;
}

法二:

自定义bool比较函数,实现降序排列

#include <iostream>
#include <algorithm>
#include <vector>

using namespace std;
bool cmp(int num1, int num2) {
    return num1 > num2;     
    // " > " 降序排列
    // " < " 升序排列
}

int main() {
    //数组
    int a[10] = {3,2,1,6,5,4,9,8,7,0};
    sort(a, a + 10, cmp);  
    for (int i = 0; i < 10; i++)
        cout << a[i] << ' ';		
    //排序后数组9 8 7 6 5 4 3 2 1 0
    cout << endl;	

    //vector容器
    vector<int> arr = {3,2,1,6,5,4,9,8,7,0};
    sort(arr.begin(), arr.end(), cmp);   
    for (int i = 0; i < 10; i++) 
        cout << arr[i] << ' ';	
    //排序后数组9 8 7 6 5 4 3 2 1 0
    cout << endl;

    return 0;
}

记于2024.10.2

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值