问题
I want to define a recursive function can sort any 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 this function on a list [3, 1, 2,4,7,5,6,9,8] should give me:
[1,2,3,4,5,6,7,8,9]
But I get:
print(sort_l([3, 1, 2,4,7,5,6,9,8]))--> [1, 2, 4, 5, 6, 8, 9, 7, 3]
Please help me to fix the problem, actual code would be appreciated. Thanks!
回答1:
The quick sort is recursive and easy to implement in Python:
def quick_sort(l):
if len(l) <= 1:
return l
else:
return quick_sort([e for e in l[1:] if e <= l[0]]) + [l[0]] +\
quick_sort([e for 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]
回答2:
For this you would want to use merge sort. Essentially in a merge sort you recursively split the list in half until you have single elements and than build it back up in the correct order. merge sort on has a complexity of O(n log(n))
and is an extremely stable sorting method.
Here are some good in depth explanations and visuals for merge sorting:
- https://www.youtube.com/watch?v=vxENKlcs2Tw
- http://www.princeton.edu/~achaney/tmve/wiki100k/docs/Merge_sort.html
回答3:
def quicksort(lst):
"Quicksort over a list-like sequence"
if len(lst) == 0:
return lst
pivot = lst[0]
pivots = [x for x in lst if x == pivot]
small = quicksort([x for x in lst if x < pivot])
large = quicksort([x for x in lst if x > pivot])
return small + pivots + large
Above is a more readable recursive implementation of Quick Sort Algorithm. Above piece of code is from book Functional programing in python by O'REILLY.
Above function will produce.
list=[9,8,7,6,5,4]
quicksort(list)
>>[4,5,6,7,8,9]
回答4:
def sort(array, index = 0, bigNumber = 0):
if len(array) == index:
return array
elif bigNumber > array[index]:
array[index - 1] = array[index]
array[index] = bigNumber
bigNumber = array[0]
index = 0
else:
bigNumber = array[index]
return sort(array, (index + 1), bigNumber)
来源:https://stackoverflow.com/questions/26858358/a-recursive-function-to-sort-a-list-of-ints