Skip to content

Instantly share code, notes, and snippets.

@pbondoer
Created December 15, 2014 22:08
Show Gist options
  • Save pbondoer/2789b8bcf7458edb680b to your computer and use it in GitHub Desktop.
Save pbondoer/2789b8bcf7458edb680b to your computer and use it in GitHub Desktop.
Tri quicksort
# 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