Skip to content

Instantly share code, notes, and snippets.

@Babbleshack
Created April 28, 2017 14:44
Show Gist options
  • Select an option

  • Save Babbleshack/ad8158a313b698663d8b320b8d0509ff to your computer and use it in GitHub Desktop.

Select an option

Save Babbleshack/ad8158a313b698663d8b320b8d0509ff to your computer and use it in GitHub Desktop.
Insertion sort for algo course
from random import randint
vals = list()
saved_vals = list()
"""
Sort Ascending
"""
def sort(values):
for idx, key in enumerate(values[1:]):
#idx = idx - 1
while idx >= 0 and values[idx] > key:
values[idx + 1] = values[idx]
idx = idx - 1
values[idx + 1] = key
"""
Sort Descending
"""
def reverse_sort(values):
for idx, key in enumerate(values[1:]):
#idx = idx - 1
while idx >= 0 and values[idx] < key:
values[idx + 1] = values[idx]
idx = idx - 1
values[idx + 1] = key
"""
reset values
"""
def get_vals():
global saved_vals, vals
if not saved_vals:
for i in range(randint(5,9)):
saved_vals.append(randint(0,99))
vals = saved_vals[:]
get_vals()
print 'unsorted list = {}'.format(str(vals))
sort(vals)
print "Sorted {}".format(str(vals))
get_vals()
#print "Reset {}".format(str(vals))
reverse_sort(vals)
print "Reverse Sort {}".format(str(vals))
#print 'descending sort list = {}'.format(str(vals))
#reverse_sort(vals)
#print 'ascending sort list = {}'.format(str(vals))
"""
Check if index preceding the current value, is less than the current vale
"""
def check_forward(values):
for idx, value in enumerate(values):
if idx > 0 and values[idx - 1] > value:
print "FOUND ERROR FORWARDS: {}".format(str(values))
"""
Check if index preceding the current value, is more than the current vale
"""
def check_backwards(values):
for idx, value in enumerate(values):
if idx > 0 and values[idx - 1] < value:
print "FOUND ERROR BACKWARDS: {}".format(str(values))
# Do some testing
for i in range(1000):
vals = list()
saved_vals = list()
get_vals()
sort(vals)
check_forward(vals)
get_vals()
reverse_sort(vals)
check_backwards(vals)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment