Created
March 25, 2019 01:02
-
-
Save dpapathanasiou/0e5f49173c1194d3769d630a19ae6f06 to your computer and use it in GitHub Desktop.
Quicksort in Python
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
#!/usr/bin/env python | |
""" | |
An implementation in python, inspired by the version in "Learn You | |
a Haskell for Great Good!" | |
(http://learnyouahaskell.com/recursion#quick-sort) | |
""" | |
def quicksort (a): | |
if len(a) < 2: | |
return a | |
else: | |
p = a[0] | |
l = quicksort(filter(lambda x: x <= p, a[1:])) | |
r = quicksort(filter(lambda x: x > p, a[1:])) | |
return l + [p] + r | |
""" | |
Test it, using the example arrays from the text: | |
1 - a numeric array | |
2 - a string (array of chars) | |
""" | |
narr = [10,2,5,3,1,6,7,4,2,3,4,8,9] | |
nexp = [1,2,2,3,3,4,4,5,6,7,8,9,10] | |
nres = quicksort(narr) | |
print 'sorting', narr, '->', nres | |
assert nres == nexp, 'expected ' + nexp + ' from sorting ' + narr + ' but got ' + nres | |
# using list() to keep the type system happy | |
sarr = list("the quick brown fox jumps over the lazy dog") | |
sexp = list(" abcdeeefghhijklmnoooopqrrsttuuvwxyz") | |
sres = quicksort(sarr) | |
print 'sorting "' + ''.join(sarr) + '" -> "' + ''.join(sres) + '"' | |
assert sres == sexp, 'expected "' + ''.join(sexp) + '" from sorting "' + ''.join(sarr) + '" but got "' + ''.join(sres) + '"' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment