一、sort函数的用法
- 必须包含头文件:
#include <algorithm>
和using namespace std;
- 时间复杂度为:
n*log2(n)
sort函数
有三个参数:(第三个参数可选
)
- 第一个是要排序的数组的起始地址
- 第二个是结束的地址(最后一位要排序的地址)
- 第三个参数是排序的方法,可以是升序也可是降序。如果不写第三个参数,则默认的排序方法是从升序排列
二、两种用法
两个参数用法(此时默认升序排列)
#include <iostream>
#include <algorithm>
using namespace std;
int main()
{
int i;
int a[10] = { 2, 4, 1, 23, 5, 76, 0, 43, 24, 65 };
for(i = 0; i < 10; i++) {
cout << a[i] << " "; //2 4 1 23 5 76 0 43 24 65
}
sort(a, a + 10);
for(i = 0; i < 10; i++) {
cout << a[i] << " "; //0 1 2 4 5 23 24 43 65 76
}
return 0;
}
三个参数的用法(可选升序或降序)
首先需要自定义一个比较函数:compare()
bool compare(int a, int b) {
//return a < b; //升序排列
return a > b; //降序排列
}
这个函数告诉程序,到底是升序
还是降序
排列。
#include <iostream>
#include <algorithm>
using namespace std;
bool compare(int a, int b) {
//return a < b; //升序排列
return a > b; //降序排列
}
int main()
{
int i;
int a[10] = { 2, 4, 1, 23, 5, 76, 0, 43, 24, 65 };
for(i = 0; i < 10; i++) {
cout << a[i] << " "; //2 4 1 23 5 76 0 43 24 65
}
cout << endl;
sort(a, a + 10, compare); //这里不需要对compare传参,这是规则
for(i = 0; i < 10; i++) {
cout << a[i] << " "; //76 65 43 24 23 5 4 2 1 0
}
return 0;
}
也可以不自定义一个比较函数,可以调用标准库里的模板:
这里会用到:functional
头文件,所以别忘了加上#include <functional>
functional
提供了一堆基于模板的比较函数对象。它们是(看名字就知道意思了):equal_to、not_equal_to、greater、greater_equal、less、less_equal。对于这个问题来说,greater和less就足够了,直接拿过来用:
- 升序:
sort( begin, end, less<data-type>() );
- 降序:
sort( begin, end, greater<data-type>() );
# include <iostream>
# include <algorithm>
# include <functional>
using namespace std;
int main()
{
int i;
int a[10] = { 2, 4, 1, 23, 5, 76, 0, 43, 24, 65 };
for (i = 0; i < 10; i++) {
cout << a[i] << " "; //2 4 1 23 5 76 0 43 24 65
}
cout << endl;
//升序
sort( a, a + 10, less<int>() );
for (i = 0; i < 10; i++) {
cout << a[i] << " "; //0 1 2 4 5 23 24 43 65 76
}
cout << endl;
//降序
sort( a, a + 10, greater<int>() );
for (i = 0; i < 10; i++) {
cout << a[i] << " "; //76 65 43 24 23 5 4 2 1 0
}
cout << endl;
return 0;
}
三、对字符串型的数据排序
1.使用迭代器,顺序排列:
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
int main()
{
string str = "hello world";
sort( str.begin(), str.end() );
cout << str; //空格dehllloorw //注意空格
return 0;
}
2.使用反向迭代器,逆序排列:
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
int main()
{
string str = "hello world";
sort( str.rbegin(), str.rend() );
cout << str; //wroolllhed空格 //注意空格
return 0;
}
使用IDE:CodeBlocks
结语:文章有错误或不足,欢迎评论,希望轻拍,一起进步哦!
END!
还没有人抢沙发呢~