python - A recursive function to sort a list of ints -


i want define recursive function can sort list of ints:

def sort_l(l):     if l==[]:         return []     else:         if len(l)==1:             return [l[-1]]         elif l[0]<l[1]:             return [l[0]]+sort_l(l[1:])         else:             return sort_l(l[1:])+[l[0]] 

calling function on list [3, 1, 2,4,7,5,6,9,8] should give me:

[1,2,3,4,5,6,7,8,9] 

but get:

print(sort_l([3, 1, 2,4,7,5,6,9,8]))--> [1, 2, 4, 5, 6, 8, 9, 7, 3] 

please me fix problem, actual code appreciated. thanks!

the quick sort recursive , easy implement in python:

def quick_sort(l):     if len(l) <= 1:         return l     else:         return quick_sort([e e in l[1:] if e <= l[0]]) + [l[0]] +\             quick_sort([e e in l[1:] if e > l[0]]) 

will give:

>>> quick_sort([3, 1, 2, 4, 7, 5, 6, 9, 8]) [1, 2, 3, 4, 5, 6, 7, 8, 9] 

Comments

Popular posts from this blog

c++ - QTextObjectInterface with Qml TextEdit (QQuickTextEdit) -

javascript - angular ng-required radio button not toggling required off in firefox 33, OK in chrome -

xcode - Swift Playground - Files are not readable -