Skip to content

Instantly share code, notes, and snippets.

@joelgrus
Last active August 29, 2015 14:10
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save joelgrus/9dc47ebb22243fe990e5 to your computer and use it in GitHub Desktop.
Save joelgrus/9dc47ebb22243fe990e5 to your computer and use it in GitHub Desktop.
non-recursive quicksort, based on http://bertrandmeyer.com/2014/12/07/lampsort/
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