Search code examples
pythonpython-2.7insertion-sort

Insertion sort not working - list index out of range


Trying to create insertion sort but receive an error...

Don't really know why it is happening. It always tends to miss 37 aswell

numbers = [45,56,37,79,46,18,90,81,50]

def insertionSort(items):
    Tsorted = []
    Tsorted.append(items[0])
    items.remove(items[0])
    for i in range(0,len(items)):
        print (Tsorted)
        if items[i] > Tsorted[len(Tsorted)-1]:
            Tsorted.append(items[i])
        else:
            Tsorted[len(Tsorted)-2] = items[i]
        items.remove(items[i])

insertionSort(numbers)

Error:

    if items[i] > Tsorted[len(Tsorted)-1]:
IndexError: list index out of range

Solution

  • First thing: you are removing items from the Array that you are iterating inside the loop here: items.remove(items[i]). This is generally not a good idea.

    Second: This algorithm doesn't implement insertion sort, even if you fix the deletion issue. You should review the algorithm, e.g. here Insertion sort in Wikipedia. Thre is another loop required to find the right insertion place.

    Third: in the else case, you are overwriting instead of inserting values.