Implementing insertion sort

In this step, you are going to implement insertion sort in Python.

To start with — just like bubble sort — you need a short list to test your algorithm on.

my_list = [5,9,5,8,1,3]

You should write the algorithm as a function, again with a single parameter (the list to be sorted). Make sure to comment your code to explain what each part is accomplishing.

def insertion_sort(list_to_sort):

Requirements

Your function needs to do the following:

Code snippets

Here are a few code snippets to help you implement this algorithm, you will have to change these to suit your program:

for item in range(1, len(list_to_sort))

The variable item will start with a value of 1 rather than 0.

key = list_to_sort[item]

while item > 0 and item < 10:

Make sure that both sides of the and are full condition statements. A common mistake is to write a loop like this: while item > 0 and < 10 but this will cause a syntax error.

list_to_sort[marker + 1] = list_to_sort[marker]

This does not swap the items, rather it just copies the value from the marker’s position to the next one along in the list. It is important that you have the current item stored in a variable so it can be replaced when you find the right spot.

Have a go at generating the algorithm. If you get stuck, ask for help in the comments below. If you get totally lost, then you can have a peek at a solution on Rosetta Code. These examples have not used relevant names for their variables, be sure that your function uses variable names that relate to the data stored in that variable.