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
i--;
}
a[i+1]=key;//Insertion
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)