The basic idea of direct insertion sorting is to insert the records to be sorted in sequence to the proper position of the sorted records sub-sequence according to their key code. There are N records in the list of sequence tables to be sorted. At the beginning, there is only one record list [0] In the subsequence. During the first sorting, compare list [1] With list [0]. If list [0] <= list [1], no sorting is required. Otherwise, the position is changed, in the second sorting, list [2] and list [1] compare the size. If list [2] is smaller than list [1], then it is compared with list [0, insert it to the appropriate location.
Algorithm As follows:
First, identify an array to be sorted:
Int [] array = new int [6] {2, 1, 4, 3, 6, 5 };
Below is the sorting Code :
I. DESC Method Static Void Descinsertsort ( Int [] Array)
{
For ( Int I = 1 ; I < Array. length; I ++ )
{
If (Array [I] > Array [I - 1 ])
{
Int TMP = Array [I];
Int J = 0 ;
For (J = I - 1 ; J > = 0 && TMP > Array [J]; -- J)
{
Array [J + 1 ] = Array [J];
}
Array [J + 1 ] = TMP;
}
}
}
Ii. ASC Method Static Void Ascinsertsort ( Int [] Array)
{
For ( Int I = 1 ; I < Array. length; I ++ )
{
If (Array [I] < Array [I - 1 ])
{
Int TMP = Array [I];
Int J = 0 ;
For (J = I - 1 ; J > = 0 && TMP < Array [J]; -- J)
{
Array [J + 1 ] = Array [J];
}
Array [J + 1 ] = TMP;
}
}
}
The following is the test code: Static Void Main ( String [] ARGs)
{
Try
{
Int [] Array = New Int [ 6 ] { 2 , 1 , 4 , 3 , 6 , 5 };
Console. writeline ( " ---- DESC ---- " );
Descinsertsort (array );
For ( Int I = 0 ; I < Array. length; I ++ )
{
Console. writeline (array [I]);
}
Console. writeline ( " ---- ASC ---- " );
Ascinsertsort (array );
For ( Int I = 0 ; I < Array. length; I ++ )
{
Console. writeline (array [I]);
}
Console. Readline ();
}
Catch (Exception ex)
{
Console. writeline (ex. Message );
Console. Readline ();
}
}
The result is as follows: