Sort--insert sort (loop invariant)

Source: Internet
Author: User

The idea of inserting a sort is to construct a cyclic invariant, the use of poker examples to explain that the left hand is already lined up cards, the right hand is not a good order of cards, the right hand of the cards in turn one by one inserted into the left hand, each card in the left hand in turn and this card comparison, in order to determine this card in the left hand in the correct order, Then proceed to the next card, in this process, the left hand card is always in order, that is, constant,--called cyclic invariant

Initial: Only one card in the left hand, is a good order

Hold: Insert the hands in the right hand position, keep the left hand orderly

To terminate: When the hands of the hand are all in the left hand

Initial: Only 1, already sequenced.

Hold: while (I>=1&&a[i]>key)


a[i+1]=a[i]//Right Shift




The code that has been run is as follows

#defineN 10intMain () {intI=0; intA[n];  for(i=0; i<n;i++) scanf ("%d",&A[i]); intJ,key; I=0;  for(j=1; j<n;j++) {Key=A[j]; I=j-1;  while(i>=0&&a[i]<key) {A[i+1]=A[i]; I--; } a[i+1]=key; }     for(i=0; i<n;i++) {printf ("%d\t", A[i]); }    return 0;}

Sort--insert sort (loop invariant)

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: 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.