C # data structure and algorithm series (6) Direct insertion sorting

Source: Internet
Author: User

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:

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.