【c++】排序还在用冒泡排序?快来了解sort函数

简介: 【c++】排序还在用冒泡排序?快来了解sort函数

C++中的的sort函数


冒泡排序执行效率低,这样看来就不如我们使用简单好操作的sort函数


sort 排序函数


必须要有的头文件: #include < algorithm > 拥有三个参数:sort(a,b,c) a:第一个是要排序的数组的起始地址。 b:第二个是结束的地址(最后一位要排序的地址)。 c:第三个参数是排序的方法。


下面就具体使用sort()函数结合对数组排序做一个说明!


1.sort函数若没有第三个参数,默认实现的是从小到大


#include<iostream>
#include<algorithm>
using namespace std;
int main()
{
 int a[10]={9,6,3,8,5,2,7,4,1,0};
 for(int i=0;i<10;i++)
 cout<<a[i]<<endl;
sort(a,a+10);  
 for(int i=0;i<10;i++)
 cout<<a[i]<<endl;
 return 0;
}


2.sort函数的第三个参数



greater<数据类型>() //从大到小排序
#include<iostream>
#include<algorithm>
using namespace std;
int main()
{
 int a[10]={9,6,3,8,5,2,7,4,1,0};
 for(int i=0;i<10;i++)
 cout<<a[i]<<endl;
 sort(a,a+10,greater<int>());
 for(int i=0;i<10;i++)
 cout<<a[i]<<endl;
 return 0;
}


3.利用sort函数实现对字符的排序


#include<iostream>
#include<algorithm>
using namespace std;
int main()
{
 char a[11]="asdfghjklk";
 for(int i=0;i<10;i++)
 cout<<a[i]<<endl;
 sort(a,a+10,greater<char>());
 for(int i=0;i<10;i++)
 cout<<a[i]<<endl;
 return 0;
}


相关文章
|
14天前
|
编译器 C语言 C++
【C++初阶(九)】C++模版(初阶)----函数模版与类模版
【C++初阶(九)】C++模版(初阶)----函数模版与类模版
18 0
|
25天前
|
存储 缓存 C++
C++链表常用的函数编写(增查删改)内附完整程序
C++链表常用的函数编写(增查删改)内附完整程序
|
27天前
|
存储 安全 编译器
【C++】类的六大默认成员函数及其特性(万字详解)
【C++】类的六大默认成员函数及其特性(万字详解)
35 3
|
30天前
|
安全 程序员 C++
【C++ 基本知识】现代C++内存管理:探究std::make_系列函数的力量
【C++ 基本知识】现代C++内存管理:探究std::make_系列函数的力量
101 0
|
30天前
|
设计模式 安全 C++
【C++ const 函数 的使用】C++ 中 const 成员函数与线程安全性:原理、案例与最佳实践
【C++ const 函数 的使用】C++ 中 const 成员函数与线程安全性:原理、案例与最佳实践
71 2
|
1月前
|
安全 编译器 程序员
【C++ 泛型编程 高级篇】C++ 编程深掘:静态成员函数检查的艺术与实践
【C++ 泛型编程 高级篇】C++ 编程深掘:静态成员函数检查的艺术与实践
64 0
|
1月前
|
存储 安全 编译器
【C++ 函数设计的艺术】深挖 C++ 函数参数的选择 智能指针与 std::optional:最佳实践与陷阱
【C++ 函数设计的艺术】深挖 C++ 函数参数的选择 智能指针与 std::optional:最佳实践与陷阱
110 0
|
1月前
|
安全 算法 编译器
【C++中的const函数】何时与如何正确声明使用C++ const函数(三)
【C++中的const函数】何时与如何正确声明使用C++ const函数
26 0
|
1月前
|
安全 编译器 Linux
【C++中的const函数】何时与如何正确声明使用C++ const函数(二)
【C++中的const函数】何时与如何正确声明使用C++ const函数
28 0
|
1月前
|
安全 编译器 C++
【C++中的const函数】何时与如何正确声明使用C++ const函数(一)
【C++中的const函数】何时与如何正确声明使用C++ const函数
22 0