Quick sort in Python

A milltion times already on the internet and sorting methods already integrated in the language – so why?
Because written things stay better in the brain and I like to understand things from the ground.

ArjanCodes (I love your content!) recently posted a video about recursive functions and used a similar code. I won’t have written the code if it wasn’t for the fact that he used to list comprehensions to fill the lists and for that has to iterate two times over the list. His example isn’t about performance optimisation but for showcasing recursive functions and is a little easier understand.
Please let me know in the comments how I can further optimize it!

TLDR: Here is my code variation of quick sort. It is much slower than the builtin methods.

def sort(data: list[int]) -> list[int]:
    if len(data) <= 1:
        return data
    pivot = data[-1]
    left, right = [],[]
    for x in data[:-1]:
        left.append(x) if x <= pivot else right.append(x)
    return sort(left) + [pivot] + sort(right)

If you just want to sort your list and don’t care about which sorting algorithm to use [3,1,2].sort() to sort and overwrite your current list or sorted([3,1,2]) to create a new list with the same elements in it but in sorted order. For further sorting options refer to the linked doc.

Performance comparision to built in methods

from random import randint
from time import perf_counter



def sort(data: list[int]) -> list[int]:
    if len(data) <= 1:
        return data
    pivot = data[-1]
    left, right = [],[]
    for x in data[:-1]:
        left.append(x) if x <= pivot else right.append(x)
    return sort(left) + [pivot] + sort(right)


numbers: list[int] = [randint(0, 10000) for i in range(10000)]
numbers2 = numbers.copy()

start = perf_counter()
sorted(numbers)
print(f'Took builtin sorted() \t\t{perf_counter() - start:.6f} seconds')

start = perf_counter()
numbers.sort()
print(f'Took builtin list.sort() \t{perf_counter() - start:.6f} seconds')

start = perf_counter()
sort(numbers2)
print(f'Took my quick sort \t\t\t{perf_counter() - start:.6f} seconds')

Output of the script showed very clearly that you should always use the builtin methods for much better performance.

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.