Skip to content

Instantly share code, notes, and snippets.

@coleifer
Created August 28, 2012 18:02
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 coleifer/ea97f3f60f6cafe8da99 to your computer and use it in GitHub Desktop.
Save coleifer/ea97f3f60f6cafe8da99 to your computer and use it in GitHub Desktop.
def partition(A, idx, start=0, end=None):
if end is None:
end = len(A)
pivot = A[idx]
A[idx], A[end - 1] = A[end - 1], A[idx]
pos = start
for i in range(start, end):
if A[i] < pivot:
if i != pos:
A[pos], A[i] = A[i], A[pos]
pos += 1
A[pos], A[end - 1] = A[end - 1], A[pos]
return pos
def nsmallest(A, n, start=0, end=None):
if end is None:
end = len(A)
partition_idx = partition(A, start, start, end)
if partition_idx == n:
return A[:n]
elif partition_idx < n:
return nsmallest(A, n, partition_idx + 1, end)
else:
return nsmallest(A, n, start, partition_idx)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment