Sort a part of a list in place

非 Y 不嫁゛ 提交于 2019-11-27 07:47:21
fviktor

I'd write it this way:

a[i:j] = sorted(a[i:j])

It is not in-place sort either, but fast enough for relatively small segments.

Please note, that Python copies only object references, so the speed penalty won't be that huge compared to a real in-place sort as one would expect.

if a is a numpy array then to sort [i, j) range in-place, type:

a[i:j].sort()

Example:

>>> import numpy as np
>>> a = np.array([4, 8, 1, 7, 3, 0, 5, 2, 6, 9])
>>> a[1:4].sort()
>>> a
array([4, 1, 7, 8, 3, 0, 5, 2, 6, 9])

Based on your requirements, I'd suggest creating your own sort function/ a wrapper class for the list with a sort function which staisfies your requirement.

You might consider the DSU idiom or the schwartzian transform: See http://wiki.python.org/moin/HowTo/Sorting and http://wiki.python.org/moin/PythonSpeed/PerformanceTips. I suggest you decorate with 0 up until i, the element between i and j and 0 again j onwards. Then, use a custom comparison function to return 0 if either x or y is zero get the sort to work! This may not help, since we crossed Python V2.4 long ago. Still, this might be what you are looking for.

This answer fills in while I try figure out if it can be done with less effort!

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