Python quicksort list return

Viewed 32

My code is:

def quicksort(array):
    if len(array) <2:
        return array
    else:
        pivot = array[0]
        less = [i for i in array[1:] if i <= pivot]
        greater = [i for i in array[1:] if i > pivot]
        
        return quicksort(less) + [pivot] + quicksort(greater)
list = [10,5,2,3]
list.quicksort()
print (list)

I receive an error related to printing the list - is there a way to do this with print quicksort([10, 5, 2, 3])?

I'm looking to return the sorted list

1 Answers
def quicksort(array):
    if len(array) <2:
        return array
    else:
        pivot = array[0]
        less = [i for i in array[1:] if i <= pivot]
        greater = [i for i in array[1:] if i > pivot]
        
        return quicksort(less) + [pivot] + quicksort(greater)
a = [10,5,2,3]
print(quicksort(a))

Output:

[2, 3, 5, 10]
Related