What is the space complexity of the python sort?

柔情痞子 提交于 2020-01-03 11:23:52

问题


What space complexity does the python sort take? I can't find any definitive documentation on this anywhere


回答1:


Space complexity is defined as how much additional space the algorithm needs in terms of the N elements. And even though according to the docs, the sort method sorts a list in place, it does use some additional space, as stated in the description of the implementation:

timsort can require a temp array containing as many as N//2 pointers, which means as many as 2*N extra bytes on 32-bit boxes. It can be expected to require a temp array this large when sorting random data; on data with significant structure, it may get away without using any extra heap memory.

Therefore the worst case space complexity is O(N) and best case O(1)




回答2:


Python's built in sort method is a spin off of merge sort called Timsort, more information here - https://en.wikipedia.org/wiki/Timsort.

It's essentially no better or worse than merge sort, which means that its run time on average is O(n log n) and its space complexity is Ω(n)



来源:https://stackoverflow.com/questions/48759175/what-is-the-space-complexity-of-the-python-sort

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!