The insertion sort maintains the two sub-arrays
within the same array. At the beginning of the sort,
the
first element of the first sub-array is considered the "sorted
array". With each pass through the loop, the next
element in
the unsorted second sub-array is placed into its proper position in
the first sorted sub-array.
The insertion sort can be very fast and
efficient when used with smaller arrays. Unfortunately, it
loses this efficiency when dealing with large amounts of
data
//
Insertion Sort Method for Descending Order
public static void InsertionSort( int [ ] num)
{
int j; // the number of items sorted so far
int key; // the item to be inserted
int i;
for (j = 1; j < num.length; j++) // Start with
1 (not 0)
{
key =
num[ j ];
for(i = j - 1; (i >= 0) && (num[ i ] < key); i--) // Smaller values are moving up
{
num[ i+1 ] = num[ i ];
}
num[ i+1 ] = key; // Put the key in its
proper location
}
} |