简体   繁体   English

排序列表上的Python排序复杂度

[英]Python sorting complexity on sorted list

What is the sort(already_sorted_list) complexity in Python? Python中sort(already_sorted_list)复杂性是什么? Does Python check if given iterable is sorted, or do I have to do it by myself? Python是否检查给定的iterable是否已排序,还是我必须自己做? I could not find it anywhere in the docs. 我在文档的任何地方都找不到它。

This is entirely implementation dependent. 完全取决于实现。 All that python guarantees is that the builtin sorting algorithm is stable (elements which compare equal retain their relative ordering). python保证的是内置排序算法是稳定的 (比较相等的元素保留其相对顺序)。 An implementation could even use a stable bubble sort if it wanted to ... 如果要实现,甚至可以使用稳定的冒泡排序。

Cpython uses TimSort (a hybrid of insertion sort an mergesort) which I believe has O(N) complexity if the input is already sorted -- It picks up the best case performance of insertion sort and the worst case performance of mergesort (O(NlogN)). Cpython使用TimSort (插入排序的合并排序合并),如果输入已经被排序,我相信它具有O(N)的复杂性-它选择了插入排序的最佳情况和合并排序的最坏情况(O(NlogN ))。

And if you're curious about the implementation, the source code has a very nice description. 而且,如果您对实现感到好奇,那么源代码将提供非常好的描述。

Python's sort is called timsort . Python的排序称为timsort Its average case performance is O(nlog(n)). 其平均案例性能为O(nlog(n))。 It performs really well with pre-sorted lists because it's implementation is designed to seek out runs of sorted elements in the list. 它与预排序列表一起使用时的性能非常好,因为它的实现旨在查找列表中已排序元素的运行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM