Last active
August 29, 2015 13:56
-
-
Save code-of-kpp/8791586 to your computer and use it in GitHub Desktop.
Short 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
import random; import operator; from six.moves import range, reduce | |
def swap(arr, iv, ip, dir): | |
if iv == ip + dir: arr[iv], arr[ip] = arr[ip], arr[iv] | |
else: arr[iv], arr[ip + dir], arr[ip] = arr[ip + dir], arr[ip], arr[iv] | |
shift = lambda (cmp, dir, arr, ip), iv: (cmp, dir, arr, ip) if cmp(arr[iv], arr[ip]) else (swap(arr, iv, ip, dir) or (cmp, dir, arr, ip + dir)) | |
def qs(arr, bgn=0, end=None): | |
if end is None: end = len(arr) - 1 - bgn | |
if end - bgn < 1: return arr | |
ip = bgn if end - bgn == 1 else random.randint(bgn + 1, end - 1) | |
_, _, _, ipl = reduce(shift, range(ip - 1, bgn - 1, -1), (operator.le, -1, arr, ip)) | |
_, _, _, ipr = reduce(shift, range(ip + 1, end + 1, +1), (operator.ge, +1, arr, ipl)) | |
return qs(arr, bgn, ipr) and qs(arr, ipr+1, end) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment