I created my own list sorting function with Python:
def mysort(l):
for i, (x, y) in enumerate(zip(l, l[1:])):
if y < x:
l[i], l[i + 1] = l[i + 1], l[i]
mysort(l)
else:
return l
And:
>>> mysort(l)
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>>
I was thinking that how I would be able to optimize this function.
This function is recursive, thus it runs many times + it has a for loop.
Would it be possible to optimize like with O(log(n))?
sortmethod. \$\endgroup\$O(log(n))?" – No, this is impossible. The lower bound for comparison-based sort is O(n log n). In other words: comparison-based sort cannot possibly be faster than O(n log n). I will not give a proof here, but the proof is not rocket science, it is routinely assigned as homework in undergrad CS courses. There are non-comparison based sorts that take advantage of additional information and structure be be faster than O(n log n), but obviously that means the additional information and structure does need to exist. Selection sort is an … \$\endgroup\$