Insertion sort not working - list index out of range
<p>Trying to create insertion sort but receive an error...</p>

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

<pre><code>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] &gt; Tsorted[len(Tsorted)-1]:
            Tsorted.append(items[i])
        else:
            Tsorted[len(Tsorted)-2] = items[i]
        items.remove(items[i])

insertionSort(numbers)
</code></pre>

<p>Error:</p>

<pre><code>    if items[i] &gt; Tsorted[len(Tsorted)-1]:
IndexError: list index out of range
</code></pre>

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

<p>Second: This algorithm doesn't implement insertion sort, even if you fix the deletion issue. You should review the algorithm, e.g. here <a href="https://en.wikipedia.org/wiki/Insertion_sort" rel="nofollow">Insertion sort in Wikipedia</a>. Thre is another loop required to find the right insertion place.</p>

<p>Third: in the else case, you are overwriting instead of inserting values.</p>

python python-2.7 insertion-sort