Skip to content

Instantly share code, notes, and snippets.

@akerbos
Created July 4, 2016 18:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save akerbos/9d708d0962a2f78d187a7f2831458d2b to your computer and use it in GitHub Desktop.
Save akerbos/9d708d0962a2f78d187a7f2831458d2b to your computer and use it in GitHub Desktop.
Dual-Pivot Quicksort
def swap(lst, i, j):
if min(i,j) >= 0 and max(i,j) < len(lst) and i != j:
lst[i], lst[j] = lst[j], lst[i]
lst.log()
# This is Dual-Pivot Quicksort by Yaroslavskiy et al.
# Implemented following Sebastian Wild as in
# https://www.uni-trier.de/fileadmin/fb4/prof/INF/TIN/Theorietag/TR.pdf
# page 39
# Plus a bugfix: need to swap pivot candidates, otherwise swapping-in pivots in the end
# does not work.
def dpquicksort(lst, left=0, right=None):
if right is None:
right = len(lst) - 1
if right - left >= 1:
if lst[left] > lst[right]:
swap(lst, left, right)
p = lst[left]
q = lst[right]
l = left + 1
g = right - 1
k = l
while k <= g:
if lst[k] < p:
swap(lst, k, l)
l += 1
elif lst[k] >= q:
while lst[g] > q and k < g:
g -= 1
swap(lst, k, g)
g -= 1
if lst[k] < p:
swap(lst, k, l)
l += 1
k += 1
l -= 1
g += 1
swap(lst, left, l)
swap(lst, right, g)
dpquicksort(lst, left, l-1)
dpquicksort(lst, l+1, g-1)
dpquicksort(lst, g+1, right)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment