Algorithm Should Not Work
2 cyberborean 3 6/14/2025, 3:06:32 PM
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
Comments (3)
gus_massa · 3h ago
Remember to add two spaces to get the correct formating:
not_your_vase · 12h ago
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.
yorwba · 12h ago
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.