Skip to content

Instantly share code, notes, and snippets.

@schlamar
Created April 5, 2013 14:28
Show Gist options
  • Save schlamar/5319691 to your computer and use it in GitHub Desktop.
Save schlamar/5319691 to your computer and use it in GitHub Desktop.
Insertion sort.
from operator import lt
def insertion_sort(data, cmp_func=lt):
for i in xrange(1, len(data)):
if cmp_func(data[i], data[i - 1]):
el = data.pop(i)
j = i - 1
while j > 0 and cmp_func(el, data[j - 1]):
j -= 1
data.insert(j, el)
return data
def test():
for i in xrange(1, 10):
data = list(reversed(range(i)))
assert insertion_sort(data) == sorted(data)
if __name__ == '__main__':
test()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment