Skip to content

Instantly share code, notes, and snippets.

@kflu
Created July 6, 2012 00:34
Show Gist options
  • Select an option

  • Save kflu/3057321 to your computer and use it in GitHub Desktop.

Select an option

Save kflu/3057321 to your computer and use it in GitHub Desktop.
Quick sort in Python (with tests)
class QSort:
def __init__(self, A):
self.A = A
def partition(self, L, U):
s = U
p = L
while s != p:
if self.A[p] <= self.A[s]:
p += 1
else:
self.swap(p,s)
self.swap(p, s-1)
s -= 1
return s
def _sort(self, L, U):
if L >= U: return
p = self.partition(L, U)
self._sort(L, p-1)
self._sort(p+1, U)
def sort(self):
self._sort(0, len(self.A)-1)
def swap(self, a, b):
self.A[a], self.A[b] = self.A[b], self.A[a]
def test_normal():
A = [8,3,4,1]
As = sorted(A)
QSort(A).sort()
assert A == As
def test_empty():
A = []
QSort(A).sort()
assert A == []
def test_1():
A = [1]
QSort(A).sort()
assert A == [1]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment