1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.
  2. Anuncie Aqui
    Anuncie aqui você Também: fdantas@4each.com.br

[Python] Quicksort Python

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

  1. Stack

    Stack Membro Participativo

    I just simply don't know where it goes wrong with my code. I'm trying to use Quicksort method to sort an array in ascending order, doesn't seem to work.

    def quicksort(array, left, right):
    if left < right:
    pivot = partition(array, left, right)
    quicksort(array, left, pivot - 1)
    quicksort(array, pivot + 1, right)
    return array

    def partition(array, left, right): #left and right are indices
    #pick the pivot as the middle element
    pivot = array[round((left + right)/2)]
    while left < right:
    while array
    < pivot:
    left += 1
    while array
    > pivot:
    right -= 1
    if left < right:
    # swap the 2 elements
    array
    , array
    = array
    , array

    left += 1
    right -= 1

    # swap the pivot and the last element (where the 2 pointers meet each other)
    array
    , array[array.index(pivot)] = array[array.index(pivot)], array

    return left


    so when

    print(quicksort([4, 6, 8, 1, 3], 0, 4))


    the result is

    [3, 4, 6, 1, 8]

    Continue reading...​

Compartilhe esta Página