Skip to content

Instantly share code, notes, and snippets.

@mb0017
Created January 15, 2014 21:46
Show Gist options
  • Save mb0017/8445364 to your computer and use it in GitHub Desktop.
Save mb0017/8445364 to your computer and use it in GitHub Desktop.
Quicksort using list comprehensions
#source: http://en.literateprograms.org/Quicksort_(Python)
def qsort1(list):
"""Quicksort using list comprehensions"""
if list == []:
return []
else:
pivot = list[0]
lesser = qsort1([x for x in list[1:] if x < pivot])
greater = qsort1([x for x in list[1:] if x >= pivot])
return lesser + [pivot] + greater
numbers = (1,6,3,32,85,23,9,123,23,336)
print qsort1(numbers)
@TheAlchemistNerd
Copy link

TheAlchemistNerd commented Jul 10, 2020

This may not be intuitive at first sight. But that's always with recursion. Through list comprehension program is reduced into two logical lines. That makes it easy to get what's going on here.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment