-
-
Save zeffii/6659494 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
# insertion_sort.py | |
import operator | |
A = [5,2,4,6,1,3] | |
print(A) | |
def sortup(A): | |
for j in range(1, len(A)): | |
key = A[j] | |
i = j - 1 | |
while (i >= 0 and A[i] > key): | |
A[i+1] = A[i] | |
i -= 1 | |
A[i + 1] = key | |
sortup(A) | |
print(A) | |
def sortdown(A): | |
for j in range(1, len(A)): | |
key = A[j] | |
i = j - 1 | |
while (i >= 0 and A[i] < key): | |
A[i+1] = A[i] | |
i -= 1 | |
A[i + 1] = key | |
A = [5,2,4,6,1,3] | |
sortdown(A) | |
print(A) | |
def sort_func(A, ascending=True): | |
ops = operator.gt if ascending else operator.lt | |
for j in range(1, len(A)): | |
key = A[j] | |
i = j - 1 | |
while (i >= 0 and ops(A[i], key)): | |
A[i+1] = A[i] | |
i -= 1 | |
A[i + 1] = key | |
sort_func(A) | |
print(A) | |
sort_func(A, ascending=False) | |
print(A) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
crappy insert sort, and function wrapper.