前言
平时写算法题时经常会用的到sort排序,本文将会从sort原理,sort在结构体,vector,map中使用方法总结
sort原理
1.数据量大时采用QuickSort快排算法,分段归并排序。
2.一旦分段后的数据量小于某个门槛(16),为避免QuickSort快排的递归调用带来过大的额外负荷,就改用Insertion Sort插入排序。
3.如果递归层次过深,还会改用HeapSort堆排序。
sort的俩种排序方式
1.从小到大(默认)
sort(nums.begin(), nums.end(),less());
2.从大到小
sort(nums.begin(), nums.end(),greater())
比较函数
针对不同的结构可以写自己的比较函数,但是比较函数要注意传的参数就是模板的类型,比如对vector排序就是传int类型
sort对结构体排序
例如对node从大到小排序
#include <iostream>
#include <algorithm>
using namespace std;
struct node
{
int a;
int b;
};
int main()
{
node nums[5];
for (int i = 0; i < 5; ++i)
{
nums[i].a = i;
nums[i].b = i;
}
sort(nums, nums + 5, [&](const node& a, const node& b) {return a.a > b.a; });
for (int i = 0; i < 5; ++i)
{
cout << nums[i].a <<" "<< nums[i].b << endl;
}
return 0;
}
sort对vector排序
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
int main()
{
vector<int> nums = { 1,4,2,5,3,7 };
sort(nums.begin(), nums.end(), [&](const int& a, const int& b) {return a < b; });
for (int i : nums)
cout << i<<endl;
return 0;
}