Insertion Sort

Insertion sort is similar to the way people sort playing cards: given some cards that are sorted and a new card to be added, make a hole where the new card should go and put the new card into the hole.


public static void insertionSort( Integer[] a ) {
  for ( int i = 1; i < a.length; i++ )
    {   int hole;
        Integer item = a[i];
        for ( hole = i;
              hole > 0 &&
                item.compareTo( a[hole - 1] ) < 0;
              hole-- )
            a[hole] = a[hole - 1];
        a[hole] = item; } }

Contents    Page-10    Prev    Next    Page+10    Index