Insertion Sort

Insertion sort works the way many people sort a bridge or gin rummy hand.  We start with an empty left hand and the cards face down on the table.  We then remove one card at a time from the table and insert it into the correct position in the left hand.  To find the correct position for a card, we compare it with each of the cards already in the hand, from right to left.

Input:     The sequence s = [s(1), s(2), .., s(n)] and the length n of the sequence.
Output:  The sequence s arranged in increasing order.

1. procedure insertion_sort(s, n)
2.   if n = 1 then            // base case
3.     return
4.   insertion_sort(s, n-1)   // recursive call
5.   i := n-1
6.   temp = s(n)
7.   while i >= 1 and s(i) > temp do   // count this comparison
8.     begin
9.     s(i+1) := s(i)     // shift elements from right
10.    i := i - 1
11.    end
12.  s(i+1) := temp       // insert at correct position
13.end insertion_sort