排序算法 | sort函数的使用

除了我们自己写的排序算法:冒泡排序、选择排序等,C语言中提供了库函数qsort或者C++中提供了sort函数可以直接调用进行排序。考虑到qsort函数的使用需要用到指针,且写法上也没有sort函数简洁。因此推荐使用C++中的sort函数,本文就是对sort函数的总结啦!

 

sort函数可以根据不同情形使用不同的排序方法,使得排序效率增高。关于其的实现这里就不细述啦,只要明白怎么调用它来完成我们的排序就行。

 

一、sort函数的简单使用

sort函数在C++的 "algorithm"库中,使用前要加上头文件 "#include <algorithm>""using namespace std;"

调用方式如下:

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

注意:

  1.  在不传入比较函数这一变量时,sort函数默认增序排序
  2.  对char型数组排序,默认字典序
  3.  在不传入比较函数时调用sort函数,传入的元素之间要有可比性,如:均为一种类型。

来看看函数对int型数组排序的应用:

//
// Created by LittleCat on 2020/2/11.
//

#include <algorithm>

using namespace std;

int main() {
    int a[6] = {4, 2, 1, 6, 3, 5};
    //对a[0]~a[3]排序
    sort(a, a + 4);
    //输出结果 1 2 4 6 3 5
    for(int i:a)
        printf("%d ", i);
}

 

二、实现比较函数cmp

待排序的序列中的元素一定要有可比性,因此需要制定排序规则来建立这种可比性。特别像结构体,本身不具备大小关系,应该如何排序呢?这就需要认为指定比较的规则了。sort函数的第三个传入参数为一个函数,一般写做cmp函数,用来指定比较的规则

 

1、基本数据类型

之前已经说明:在不传入比较函数这一变量时,sort函数默认增序排序。

//
// Created by LittleCat on 2020/2/11.
//

#include <algorithm>

using namespace std;

int main() {
    int a[6] = {4, 2, 1, 6, 3, 5};
    //对a[0]~a[3]排序
    sort(a, a + 4);
    //输出结果 1 2 4 6 3 5
    for(int i:a)
        printf("%d ", i);
}

如果需要降序排序,则要使用传入比较函数cmp来告诉sort函数何时需要交换元素(让元素的大小比较关系反过来)。还是上面那个例子,将其用降序排序:

//
// Created by LittleCat on 2020/2/11.
//

#include <algorithm>

using namespace std;

bool cmp(int x, int y) {
    return x > y;  //可以理解为:如果a>b,则将a放在b的前面
}

int main() {
    int a[6] = {4, 2, 1, 6, 3, 5};
    //对a[0]~a[3]排序
    sort(a, a + 4, cmp);
    //输出结果 6 4 2 1 3 5
    for (int i:a)
        printf("%d ", i);
}

2、结构体类型

假设现在定义了如下结构体数组:

struct node {
    int x;
    int y;
} a[6];

那么要对这个结构体排序,我们的排序规则是什么呢?可以按照x的大小来排序、也可以按找y的大小来排序。不同的排序规则需要传入不同的cmp函数,下面就是两种排序规则的应用:

//
// Created by LittleCat on 2020/2/11.
//

#include <algorithm>

using namespace std;

struct node {
    int x;
    int y;
} a[6];

bool cmp1(struct node m, struct node n) {
    return m.x > n.x;
}

bool cmp2(struct node m, struct node n) {
    return m.y > n.y;
}


int main() {
    a[0].x = -1, a[0].y = 0;
    a[1].x = 1, a[1].y = 2;
    a[2].x = 21, a[2].y = -12;
    a[3].x = -3, a[3].y = 22;
    a[4].x = 9, a[4].y = 11;
    a[5].x = 4, a[5].y = 5;

    //按照x降序排序
    sort(a, a + 6, cmp1);
    //输出结果:
    // 21 -12
    //  9  11
    //  4   5
    //  1   2
    // -1   0
    // -3  22
    for (struct node i : a)
        printf("%3d %3d\n", i.x, i.y);


    //按照y降序排序
    sort(a, a + 6, cmp2);
    //输出结果:
    // -3  22
    //  9  11
    //  4   5
    //  1   2
    // -1   0
    // 21 -12
    for (struct node i : a)
        printf("%3d %3d\n", i.x, i.y);

}

 

3、STL容器类型

未完待续...

 



end 

欢迎关注个人公众号 鸡翅编程 ”,这里是认真且乖巧的码农一枚。

---- 做最乖巧的博客er,做最扎实的程序员 ----

旨在用心写好每一篇文章,平常会把笔记汇总成推送更新~

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值