如何使用sort排序函数??

转载自:https://blog.csdn.net/w_linux/article/details/76222112

最近在刷ACM经常用到排序,以前老是写冒泡,可把冒泡带到OJ里后发现经常超时,所以本想用快排,可是很多学长推荐用sort函数,因为自己写的快排写不好真的没有sort快,所以毅然决然选择sort函数

用法
1、sort函数可以三个参数也可以两个参数,必须的头文件#include < algorithm>和using namespace std;
2、它使用的排序方法是类似于快排的方法,时间复杂度为n*log2(n)

3、Sort函数有三个参数:(第三个参数可不写)

(1)第一个是要排序的数组的起始地址。

(2)第二个是结束的地址(最后一位要排序的地址)

(3)第三个参数是排序的方法,可以是从大到小也可是从小到大,还可以不写第三个参数,此时默认的排序方法是从小到大排序。

两个参数用法
#include
#include
int main()
{
int a[20]={2,4,1,23,5,76,0,43,24,65},i;
for(i=0;i<20;i++)
cout<<a[i]<<endl;
sort(a,a+20);
for(i=0;i<20;i++)
cout<<a[i]<<endl;
return 0;
}
1
2
3
4
5
6
7
8
9
10
11
12
输出结果是升序排列。(两个参数的sort默认升序排序)

三个参数
// sort algorithm example
#include // std::cout
#include // std::sort
#include // std::vector

bool myfunction (int i,int j) { return (i<j); }//升序排列
bool myfunction2 (int i,int j) { return (i>j); }//降序排列

struct myclass {
bool operator() (int i,int j) { return (i<j);}
} myobject;

int main () {
int myints[8] = {32,71,12,45,26,80,53,33};
std::vector myvector (myints, myints+8); // 32 71 12 45 26 80 53 33

// using default comparison (operator <):
std::sort (myvector.begin(), myvector.begin()+4); //(12 32 45 71)26 80 53 33

// using function as comp
std::sort (myvector.begin()+4, myvector.end(), myfunction); // 12 32 45 71(26 33 53 80)
//std::sort (myints,myints+8,myfunction);不用vector的用法

// using object as comp
std::sort (myvector.begin(), myvector.end(), myobject); //(12 26 32 33 45 53 71 80)

// print out content:
std::cout << “myvector contains:”;
for (std::vector::iterator it=myvector.begin(); it!=myvector.end(); ++it)//输出
std::cout << ’ ’ << *it;
std::cout << ‘\n’;

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
26
27
28
29
30
31
32
33
34
string 使用反向迭代器来完成逆序排列
#include
using namespace std;
int main()
{
string str(“cvicses”);
string s(str.rbegin(),str.rend());
cout << s <<endl;
return 0;
}
//输出:sescivc

作者:浅然_
来源:CSDN
原文:https://blog.csdn.net/w_linux/article/details/76222112
版权声明:本文为博主原创文章,转载请附上博文链接!

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值