Last active
September 5, 2017 03:07
-
-
Save joshuatvernon/634e0d912401899af0fdc4e23c94192b to your computer and use it in GitHub Desktop.
A functional quicksort
This file contains 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 random import randint | |
# Quicksort with starting index as pivot | |
def qsort(items): | |
if len(items) < 2: | |
return items | |
pivot = items[0] | |
left = list(filter(lambda x: x <= pivot, items[1:])) | |
right = list(filter(lambda x: x > pivot, items[1:])) | |
return qsort(left) + [pivot] + qsort(right) | |
# Quicksort implemented with a random pivot | |
def qsort(items): | |
if len(items) < 2: | |
return items | |
p_i = randint(0, len(items) - 1) | |
pivot = items[p_i] | |
left = list(filter(lambda x: x <= pivot, items[:p_i] + items[p_i + 1:])) | |
right = list(filter(lambda x: x > pivot, items[:p_i] + items[p_i + 1:])) | |
return quicksort(left) + [pivot] + quicksort(right) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment