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.
The algorithm is as follows:
First, identify an array to be sorted:
Int [] array = new int [6] {2, 1, 4, 3, 6, 5 };
The following 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: