Created
January 15, 2014 21:46
-
-
Save mb0017/8445364 to your computer and use it in GitHub Desktop.
Quicksort using list comprehensions
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
#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) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.