Last active
August 29, 2015 14:10
-
-
Save joelgrus/9dc47ebb22243fe990e5 to your computer and use it in GitHub Desktop.
non-recursive quicksort, based on http://bertrandmeyer.com/2014/12/07/lampsort/
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
from collections import deque | |
def partition(a, lo, hi): | |
"""partition a[lo] to a[hi] using a[hi] as the pivot""" | |
pivot_value = a[hi] | |
insert_at = lo | |
for i in range(lo, hi): | |
if a[i] < pivot_value: | |
a[i], a[insert_at] = a[insert_at], a[i] | |
insert_at += 1 | |
a[hi], a[insert_at] = a[insert_at], a[hi] | |
return insert_at | |
def lampsort(a): | |
"""non-recursive quicksort using a deque of intervals | |
see http://bertrandmeyer.com/2014/12/07/lampsort/""" | |
intervals = deque([(0, len(a) - 1)]) | |
while intervals: | |
lo, hi = intervals.popleft() | |
if lo >= hi: continue | |
pivot = partition(a, lo, hi) | |
intervals.append((lo, pivot - 1)) | |
intervals.append((pivot + 1, hi)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment