[Python] Quicksort implementation in Python

Discussão em 'Python' iniciado por Stack, Maio 21, 2025.

  1. Stack

    Stack Membro Participativo

    I'm trying to implement quicksort in python. However, my code doesn't properly sort (not quite). For example, on the input array [5,3,4,2,7,6,1], my code outputs [1,2,3,5,4,6,7]. So, the end result interposes the 4 and 5. I admit I am a bit rusty on python as I've been studying ML (and was fairly new to python before that). I'm aware of other python implementations of quicksort, and other similar questions on Stack Overflow about python and quicksort, but I am trying to understand what is wrong with this chunk of code that I wrote myself:

    #still broken 'quicksort'

    def partition(array):
    pivot = array[0]
    i = 1
    for j in range(i, len(array)):
    if array[j] < array:
    temp = array
    array = array[j]
    array[j] = temp
    i += 1
    array[0] = array
    array = pivot
    return array[0:(i)], pivot, array[(i+1):(len(array))]

    def quick_sort(array):
    if len(array) <= 1: #if i change this to if len(array) == 1 i get an index out of bound error
    return array

    low, pivot, high = partition(array)
    #quick_sort(low)
    #quick_sort(high)

    return quick_sort(low) + [pivot] + quick_sort(high)

    array = [5,3,4,2,7,6,1]

    print quick_sort(array)
    # prints [1,2,3,5,4,6,7]

    Continue reading...

Compartilhe esta Página