|
The insertion sort algorithm maintains the two sub-arrays
within the same array. When the sort first begins, the
first element in the array is considered to be the "sorted
array". With each iteration of the loop, the next value in
the unsorted section is placed into its proper position in
the sorted section.
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 insertion_sort( int [ ] array)
{
int j; // the number of items sorted so far
int key; // the item to be inserted
int i;
for (j = 1; j < array.length; j++)
//Notice starting with
1 (not 0)
{
key = array[ j ];
for(i = j - 1; (i >= 0) && (array[ i ] < key); i--)
//Move smaller values up one position
{
array[ i+1 ] = array[ i ];
}
array[ i+1 ] = key;
//Insert key into
proper position
}
} |