Created
October 1, 2021 12:15
-
-
Save ohaval/23c7b4e258e20cc00da90f2d6655f08d to your computer and use it in GitHub Desktop.
The Quicksort algorithm simple and readable implementation in Python
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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