Remember to add two spaces to get the correct formating:
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
> 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
i's value doesn't persist between loops, it's a brand new i in every iteration of a for range loop. One loops modifications have no effect on the next loop. If it was c or a similar language's classic for-loop, then modifying the loop variable would be risky. But it is not the case here.
Try stepping through it in a debugger and pay attention to the values of variables vs. what you think those values should be. Or make every second line be print(locals()) and read the trace.
Remember to add two spaces to get the correct formating:
Try stepping through it in a debugger and pay attention to the values of variables vs. what you think those values should be. Or make every second line be print(locals()) and read the trace.