Insertion sort algorithm

   
        
Comparisons done:
Elements moved:
Legend:
13 - elements being compared
27 - sorted part of the array
7 - element being moved down
20 - right position for the current element
17 - current element
  Operation performing:

The insertion sort algorithm works as follows.

As you can guess, this method is called insertion sort because it inserts the current element in the right position of the sub-array.

Although it is easier to explain the idea of the insertion sort in two consecutive steps - first, find the right position, and second, insert the current element into the right position moving all elements starting from this position down, it is much more efficient to implement these two steps together in one loop. Lets compare two functions:
void isort(int data[], int N)
{
   int i, j, k, s;
   for(i=1;i<N;i++){
      s = data[i];
      // find the right spot for the element s
      for(j=i-1;j>=0 && data[j]>s;j--);
      // now j+1 is the index of the position where s should be
      // move all elements [j+1, i-1] down
      for(k=i;k>j+1;k--)
         data[k] = data[k-1];
      // put s in the right spot
      if( j < i-1 )
         data[j+1] = s;
   }
}
void isort(int data[], int N)
{
   int i, j, s;
   for(i=1;i<N;i++){
      s = data[i];
      // start moving all elements greater than s down
      for(j=i-1; j>=0 && data[j]>s; j--)
         data[j+1] = data[j];
      // put s in the right spot
      if( j < i-1 )
         data[j+1] = s;
    }
}
Below you can see the table that shows how runtime (in milliseconds) of these versions differ.

N One loop Two loops % slower
20,000 172 282 64%
40,000 656 1,062 62%
80,000 2,669 4,191 57%
160,000 11,734 18,737 59%