Created
December 15, 2014 22:08
-
-
Save pbondoer/2789b8bcf7458edb680b to your computer and use it in GitHub Desktop.
Tri 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
# quicksort implementation | |
# based on: | |
# http://me.dt.in.th/page/Quicksort/ | |
import random | |
def quicksort(a, start=0, end=None): | |
# first pass of the algorithm? | |
if end is None: | |
end = len(a) - 1 | |
# one element is always sorted! | |
if start >= end: | |
return | |
# pick random pivot, swap with first element | |
pivot = random.randint(start, end) | |
a[pivot], a[start] = a[start], a[pivot] | |
pivot = start | |
# partition from first element | |
last = start | |
for i in range(start + 1, end + 1): | |
if(a[i] < a[pivot]): | |
last += 1 | |
a[i], a[last] = a[last], a[i] | |
a[pivot], a[last] = a[last], a[pivot] | |
pivot = last | |
# run the algorithm on the two subpartitions (pivot excluded as it is sorted) | |
quicksort(a, start, pivot - 1) | |
quicksort(a, pivot + 1, end) | |
# test | |
array = random.sample(range(10), 10) | |
print(array) | |
quicksort(array) | |
print(array) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment