Below is a python program that performs an insertion sort. The main problem area is that "i" is changed within a loop the depends on i. This is very bad practice and will obviously lead to unexpected outcomes, but so far I have not been able to find an array that it does not work on. Can anyone figure out why it works?
def insertionSort(array):
for i in range(1, len(array)):
temp = array[i]
tempPos = i-1
flag = False
while flag == False and tempPos > -1:
print(array)
if temp < array[tempPos]:
array[i] = array[tempPos]
array[i-1] = temp
tempPos = tempPos - 1
i = i - 1
else:
flag = True
yorwba•14h ago