C++中sort函数从大到小排序的两种方法

发布时间:2024-03-29 16:01

参考链接:https://blog.csdn.net/lytwy123/article/details/84503492

1.sort函数描述

\"\"
而且,sort函数的算法效率相当于快排,使用sort函数有时候可能比我们自己写一个排序算法,可能效率更高。

2.使用sort函数排序

#include 
#include 
using namespace std;
int main() {
    int arr[] = {2, 4, 5, 3, 1};
    return 0;
}

  
    
    
    
    
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

这段代码我们可以在return 0前加入sort函数进行排序
sort(arr, arr + 5);
这样的操作就是对0到4号元素进行排序
\"\"
sort函数默认是进行升序排序。

有两种方式可以进行降序,可自由选择
a.使用greater()
\"\"
如果排序其他类型可更改参数
代码:

#include 
#include 
using namespace std;
int main() {
    int arr[] = { 2, 4, 5, 3, 1 };
    sort(arr, arr + 5, greater<int>());
    for(int i = 0;i < 5;i++){
    	cout<< arr[i] <<\" \";
    } 
    return 0;
}

  
    
    
    
    
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

b.自定义一个比较大小的函数,将大的排前面
自定义函数:

bool cmp(int x,int y)
{
	return x > y;
}

  
    
    
    
    
  • 1
  • 2
  • 3
  • 4

这样定义以后加入到sort函数的第三个参数即可
sort(arr,arr + 5,cmp);
源代码:

#include 
#include 
using namespace std;

bool cmp(int x,int y){
return x > y;
}

int main() {
int arr[10];
for (int i = 0; i < 10; i++) {
cin >> arr[i];
}
sort(arr,arr + 10);
for(int i = 0;i < 10;i++){
cout << arr[i] << \" \";
}
cout << endl;
sort(arr,arr + 10,cmp);
for(int i = 0;i < 10;i++){
cout << arr[i] << \" \";
}
cout << endl;
return 0;
}

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25

sort函数在算法竞赛中可以节省很多时间,推荐 大家使用
可以关注一下Blog:
http://47.107.118.184

                                

相关推荐

Halcon实例转OpenCvSharp(C# OpenCV)实现--瓶口缺陷检测(附源码)

多线程基础入门学习(带示例代码)

BI 系统中为什么会有很多快照表

element-ui一些常用组件的二次封装

【k8s部署 】k8s构建Flannel网络插件失败The connection to the server raw.githubusercontent.com was refused问题解决

目标检测指标TP、FP、TN、FN和Precision、Recall

深度学习—— Spatial Transformer Layer

2021深圳杯数学建模D题

HED 和 RCF 图像边缘检测

matlab执行m文件语句,matlab 编写m文件函数

Go语言中的Iota关键字

学习编程需要英语很好吗?

sqli-labs(less-11)

超级详细的Vue安装与配置教程

微服务SpringCloud项目:初步整合rabbitmq

<论文阅读>LVI-SAM: Tightly-coupled Lidar-Visual-Inertial Odometry via Smoothing and Mapping

ggplot2添加标签、注释。更改主题、图例、保存

docker安装ELK详细步骤

鸿蒙手机摄影,魅族官宣:你好,鸿蒙 首个第三方接入鸿蒙OS手机品牌新品亮相...

获取弹窗文本_批量下载北大法宝的法律法规文本

ItVuer - 免责声明 - 关于我们 - 联系我们

本网站信息来源于互联网,如有侵权请联系:561261067@qq.com

桂ICP备16001015号