Direct Insert sort straight insertion sort

Source: Internet
Author: User

1. The idea of direct insertion sequencing:

Insert a record into an ordered table that is already ordered, resulting in a new, sequential table with a 1 increase in the number of records.

1 voidInsertsort (SqList *L)2 {3     intI, J;4      for(i=2; i<=l->length; i++)5     {6         if(L->r[i] < l->r[i-1])7         {8l->r[0] = l->R[i];9              for(j=i-1; L-&GT;R[J] > l->r[0]; j--)Ten             { Onel->r[j+1] = l->R[j]; A             } -l->r[j+1] = l->r[0]; -         } the     } -}

2. Direct insertion sorting complexity analysis

space complexity: It only requires a record of the secondary space.

Complexity of Time:

Best case: The table itself is ordered, comparing only n-1 times, but without recording the movement, the time complexity is O (n).

Worst case scenario: The table itself is in reverse order, at which point you need to compare ∑i=2n (i) = 2+3+...+n = (n+2) (n-1)/2 times.

The number of records moved also reached the maximum ∑ni=2 (i+1) = (n+4) (n-1)/2 times.

So the average comparison and the number of moves is about N2/4 times, the time complexity is O (N2).

But the same O (N2) time complexity, the direct insert sorting method is better than bubbling and simple selection of sorting performance.

Direct Insert sort straight insertion sort

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.