Skip to content

Instantly share code, notes, and snippets.

@ohaval
Created October 1, 2021 12:15
Show Gist options
  • Save ohaval/23c7b4e258e20cc00da90f2d6655f08d to your computer and use it in GitHub Desktop.
Save ohaval/23c7b4e258e20cc00da90f2d6655f08d to your computer and use it in GitHub Desktop.
The Quicksort algorithm simple and readable implementation in Python
from typing import List, Tuple
def quick_sort(lst: List[int]) -> List[int]:
"""The Quicksort algorithm.
Wikipedia: https://en.wikipedia.org/wiki/Quicksort
"""
if len(lst) < 2:
return lst
pivot = lst[-1]
smaller, bigger = partition(lst, pivot)
bigger = quick_sort(bigger)
smaller = quick_sort(smaller)
return smaller + [pivot] + bigger
def partition(lst: List[int], pivot: int) -> Tuple[List[int], List[int]]:
"""Partition the list into 2 parts based on their relation with `pivot`.
`left` holds items smaller than `pivot`, and right holds items bigger than
`pivot`.
This function doesn't consider the last item when creating the partitions.
"""
left, right = [], []
for i in range(len(lst) - 1):
if lst[i] < pivot:
left.append(lst[i])
else:
right.append(lst[i])
return left, right
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment