Search code examples
pythonlistsortingiterationinsertion-sort

My insertion python sort is always placing the second number at the beginning


my code is working mostly fine except for a small bug where it is placing the second element at the beginning no matter the value e.g. 1,6,2,9,3,8,4,7,5,0 would become 6,0,1,2,3,4,5,7,8,9

I've tried altering the numbers in the FOR loop a bit but other than that genuinely cannot see what's wrong

def InsertionSort(array):
    for i in range(len(array)):
        for j in range(len(array)):
            if array[i] <= array[j+1]:
                new = array.pop(i)
                array.insert(j+1,new)
                break
            elif array[i] > array[j+1]:
                continue
        print (array)

Solution

  • The problem there is, that you switch the position of the second element with the first, but later on not compare it anymore.

    Here an implementation which is close to yours, with slight changes to take care of all the entries

    ar =[1,6,2,9,3,8,4,7,5,0]
    def InsertionSort(array):
        for i in range(len(array)):
                val = array[i]
                while( i > 0 and array[i-1] > val):
                    array[i] = array[i-1]
                    i = i - 1
                array[i] = val
        print (array)
    
    InsertionSort(ar)