设为首页 加入收藏

TOP

C++ 标准库 sort() / stable_sort() / partial_sort() 对比(二)
2023-07-23 13:35:09 】 浏览:56
Tags:sort stable_sort partial_sort 对比
ng namespace std; void Print(std::string message,const std::vector<int>& vec) { cout << message << ": "; for(const auto c : vec) cout << c << " "; cout <<endl; } int main() { std::vector<int> myVector{5, 7, 4, 2, 8, 6, 1, 9, 0, 3}; // 1. 以默认的排序规则 std::partial_sort(myVector.begin(),myVector.begin() + 4,myVector.end()); Print("Sorted Default", myVector); // 2. 以标准库的greater函数进行排序 std::partial_sort(myVector.begin(),myVector.end(),std::greater<int>()); Print("Sorted Standard Compare Function",myVector); // 3.以自定义的函数定义排序规则 // lamda 表达式 auto cmp1 = [](const int a,const int b) { return a < b; }; std::sort(myVector.begin(),myVector.end(),cmp1); Print("Sorted Lamda Function",myVector); return 0; }

Sorted Default: 0 1 2 3 8 7 6 9 5 4
Sorted Standard Compare Function: 9 8 7 6 5 0 1 2 3 4
Sorted Lamda Function: 0 1 9 8 7 6 5 2 3 4

* C#中的Array.Sort()

笔者在用C++复刻C#代码的时候发现对相同的数组排序的结果有时候会出现不一致,查了C#的官方文档后才发现,C#中Array.Sort()函数是unstable_sort,也就是说其排序是无法保证相对顺序的,而且Array似乎也没有提供Stable_Sort版本的排序函数,因此如果需要保证相对顺序不变,需要手动给原始的数据添加一个index,这样再其他的key判等都相等时可以采用额外的Index来保持相对的原始序。而且有意思的是,Array.Sort()函数具体使用的排序方法是根据数据规模发生改变的

-如果数据量小于等于16个,则采用插入排序
-如果需要排序的数量超过2 * log(N),其中N为输入的排序范围,则采用堆排序
-其余情况均采用快速排序
image

以上是对常用的标准库排序算法的总结和不同语言的对比,可以根据实际需要和数据量的大小来选择合适的排序算法。

首页 上一页 1 2 下一页 尾页 2/2/2
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇<四>模板的完全特例化和非.. 下一篇<八>通过new和delete重载实..

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目