Insertion sort works like a zombie librarian reordering a shelf of books
where all books on the self belong on the shelf.
Look at the first book on the shelf.
See if the call number of the next book is higher.
If it is go to the next book and repeat the process until you find a book that has that has a lower call number than the properly sequenced books before it.
Take that book out off the self and hold it in one hand.
Then move the book before it into the empty space.
See if book before the new empty space has a lower call number.
Repeat until you get to the end of the shelf
or the book to before the space
has a lower call number than the book in your hand.
Then go back to the position after the place where you found the unordered book and repeat until you get to the end of the shelf.
Lowman's method is almost the same except that it has you place the in your hand back on the shelf each time you create a new space. I'll endeavor to provide pseudo code for the more reasonable approach.
Here it goes:
Let insertion be a function that
takes in
a list,
a beginning index,*
and an ending index.*
*[the start and end indexes make the function much more useful because it can sort partial lists
or be combined with quick sort to handle shorter list fragments].
Let list be the list to be sorted.
Let a be the index for the first element to be sorted in list.
Let b be the index of the last element to be sorted in list.
Let progress be a pointer to the last sorted position in list.
Let seek be a pointer to the position where we're looking to place the unsorted element.
Let temp be an address outside of the list where we'll hold the unsorted element until we find a place for it.
Let @n be a reference to the nth element of list.
for progress, [a,b) # progress will take the values from a to b in order
#starting with a and including a, but excluding b.
if @progress+1 > @progress #check to see if the book is unsorted
then
temp = @progress+1 #take the unsorted book in hand
for seek, [progress, a) # take values from progress to a in descending order.
#Include progress, exclude a.
overwrite @seek+1 with @seek # in python: list[seek+1] = list[seek]
if seek-1 < temp #you found a place to put the book.
then
break out of this loop so you can put the book away
and find the next item to sort.
overwrite @seek with temp
And with that it should all be sorted.