Insertion Sort in Python
In an insertion sort, when processing elements to be sorted, the elements are inserted among the previously processed elements in the desired position. This is repeated from the second element to the last element.
The following is an implementation of the insertion sort algorithm in Python:
def insert_sort(a_list):
for i in range(1, len(a_list)):
val_idx = -1
for j in range(i):
if a_list[j] < a_list[i]:
val_idx = j
if val_idx is not None:
tmp_val = a_list[i]
a_list.pop(i)
a_list.insert(val_idx+1, tmp_val)
my_list = [6, 3, 5, 4, 1, 1, 2]
insert_sort(my_list)
print(my_list)