-
-
Save coleifer/ea97f3f60f6cafe8da99 to your computer and use it in GitHub Desktop.
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 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