Skip to content

Instantly share code, notes, and snippets.

@zeffii
Forked from anonymous/insertion_sort.py
Created September 22, 2013 12:34
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 zeffii/6659494 to your computer and use it in GitHub Desktop.
Save zeffii/6659494 to your computer and use it in GitHub Desktop.
# 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)
@zeffii
Copy link
Author

zeffii commented Sep 22, 2013

crappy insert sort, and function wrapper.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment