[Python] A recursive function to sort a list of ints

Discussão em 'Python' iniciado por Stack, Fevereiro 28, 2025.

  1. Stack

    Stack Membro Participativo

    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!

    Continue reading...

Compartilhe esta Página