Sort the insertion sort algorithm

Source: Internet
Author: User

Ideas:

Each iteration is compared to the previous element, and if it is less than the preceding element, the current element is swapped with the element before it, then the size of the previous element is compared and then the previous element is then exchanged. Terminates the current iteration if it is greater than the previous element. The advantage over selecting a sort is that iterations can be terminated prematurely.

Original array: 5 7 8 2 3 9

Outer Loop once: 5 7 8 2 3 9

Outer Loop two times: 5 7 8 2 3 9

Outer Loop three times: 2 5 7 8 3 9

Outer Loop four times: 2 3 5 7 8 9

Outer Loop five times: 2 3 5 7 8 9

template<classT >voidInsetsort (T data[],intilength) {     for(intn=1; n<ilength; n++)//Start comparison from the second element { for(inti = n; I>0; i--)        {            if(Data[i-1] >Data[i]) {Swap (data[i-1], data[i]); }            Else             {                 Break; }        }    }}

Optimization:

You can see that the following code replaces the above swap (three assignments) with a single assignment.

 template< class  T >void  Insetsort (T data[], int   Ilength) { for  (int  n=1 ; n<ilength;        N++ = Data[n];         int   I;//save element Temp insertion position.  for  (i = n; i> 0  && data[i- 1 ] > temp; I--) {Data[i]  = Data[i-1
     ];    } data[i]  = temp; }}

Sort the insertion sort algorithm

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.