Skip to content

Instantly share code, notes, and snippets.

@joshuatvernon
Last active September 5, 2017 03:07
Show Gist options
  • Save joshuatvernon/634e0d912401899af0fdc4e23c94192b to your computer and use it in GitHub Desktop.
Save joshuatvernon/634e0d912401899af0fdc4e23c94192b to your computer and use it in GitHub Desktop.
A functional quicksort
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