0
def sort(L,Lsorted):

    if len(L)==1:
        return Lsorted.append(L[0])
    a = min(L)
    Lsorted.append(a)
    L.remove(a)
    return sort(L,Lsorted)

The idea is that each time, you remove the smallest element of L and append to another list, and then in the end you return the other list.

This code returns None when I do this:

if __name__=='__main__':
    L = [9,1,11]
    L1 = []
    print(sort(L,L1))
Alice Li
  • 21
  • 4
  • Ow my algorithmic complexity. While `append` is amortized constant, both `min` and `remove` are linear, and since you call them repeatedly, that becomes `O(n²)`. Assuming the stack doesn't overflow first. – o11c Jan 03 '22 at 21:04
  • What is the sense of these operations when you can simply create a new list from existing list and then sort it in any direction that you need. Correct me if I'm wrong. Only if it's not about a self-training. – IgorZ Jan 03 '22 at 21:06
  • If you're deliberately studying sorting, look at: heapsort (easiest, but not stable), mergesort (easy, but requires extra memory), quicksort (usually fastest, but the worst case is very bad; not stable); insertion sort (quadratic, but such a small constant factor that it wins for small lists), selection sort (quadratic, vaguely similar to what your are attempting), bubble sort (quadratic, usually how people naively try to sort things). Other algorithms, and variations of these, exist, with different tradeoffs. – o11c Jan 03 '22 at 21:15

1 Answers1

0

.append is an in-place operation so when you return Lsorted.append(L[0]) you get back None. Try this

if len(L)==1:
    Lsorted.append(L[0])
    return Lsorted
Kraigolas
  • 5,121
  • 3
  • 12
  • 37