[Python] Why can't my Python code properly sort a list of numbers using the quick sort...

Discussão em 'Python' iniciado por Stack, Março 12, 2025.

  1. Stack

    Stack Membro Participativo

    I am using Python and trying to implement quick sort but it is not working as expected. I am providing my code below:

    def quicksort(arr):
    if len(arr) <= 1:
    return arr
    pivot = arr[0]
    left = [x for x in arr[1:] if x < pivot]
    right = [x for x in arr[1:] if x >= pivot]
    return quicksort(left) + [pivot] + quicksort(right)

    arr = [10, 2, 30, 5, 7]
    print(quicksort(arr))


    Problem: Instead of returning a sorted list, the code sometimes gives unexpected results. What I tried: I tried to change the division into left and right elements, but that didn't work. Expected result: I expect the list to be sorted in ascending order.

    Continue reading...

Compartilhe esta Página