A recursive function to sort a list of ints

后端 未结 4 668
一整个雨季
一整个雨季 2021-01-29 14:09

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:
            retur         


        
4条回答
  •  庸人自扰
    2021-01-29 14:40

    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]
    

提交回复
热议问题