Here\'s a Python implementation of insertion sort, I tried to follow the values on paper but once the counting variable i gets bigger than len(s) I don\'t know what to do, h
Try this one, works for both increasing and decreasing order:
import operator
def insertion_sort(arr, reverse=False):
# check if array is empty or not
if arr is None:
raise TypeError("Data cannot be none")
n = len(arr)
# if length of array is less than two it is already sorted
if n < 2:
return arr
lgt = operator.gt if reverse else operator.lt
# Traverse through 1 to len(arr)
for i in range(1, n):
key = arr[i]
j = i-1
while j >= 0 and lgt(key, arr[j]):
arr[j+1] = arr[j]
j -= 1
arr[j+1] = key
return arr
li = [1, 4, 8, 9, 42, 0, 36]
print(insertion_sort(li))