Insertion Sort

An insertion sort traverses a list, from the second item to the end of the list.

On each iteration, the item list[n] is placed into it’s correct position by compared it with each of the earlier items in the list, with values larger than the current  being moved up the list, until the correct location is found. 

General Algorithm

FOR i = 1 to length(list)-1 DO
    SET valueToInsert TO array[i]
    SET currentIndex TO i
 
    WHILE (currentIndex> 0) AND (valueToInsert < list[currentIndex-1]) DO
        SET list[currentIndex] TO list[currentIndex-1]
        SET currentIndex TO index - 1
    END WHILE
 
    SET list[currentIndex] TO valueToInsert 
END FOR
#work through the list from the second item to the last item
for index in range(1, len(array)):
    # get next value to be put into correct place
    currentValue = array[index]
    currentPosition = index
 
    #check if not at beginning of list, and previous item is less than value to be placed
    while currentPosition > 0 and array[currentPosition - 1] > currentValue:
        #move the lower value up a slot
        array[currentPosition] = array[currentPosition -1]
        #now for the next previous item in the list
        currentPosition = currentPosition - 1
 
    # can put value into correct slot
    array[currentPosition] = currentValue