Created
July 4, 2016 18:09
-
-
Save akerbos/a5b829d7d84af5491c294e7006dd98f7 to your computer and use it in GitHub Desktop.
Dual-Pivot Quicksort
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
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 | |
def dpquicksort(lst, left=0, right=None): | |
if right is None: | |
right = len(lst) - 1 | |
if right - left >= 1: | |
p = min(lst[left], lst[right]) | |
q = max(lst[left], 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