Reprint Please specify source: http://blog.csdn.net/ruoyunliufeng/article/details/26059615
Insert Sort: It works by constructing an ordered sequence, for unsorted data, from a backward forward scan in a sorted sequence, to find the appropriate location and insert it.
I. Insert sorting algorithm
/**************************************************************** All rights Reserved (C) 2014, company name. * * File name: Insert Sort * Content Summary: None * Other instructions: none * Current version: v1.0*: if cloud fan * finish date: 2014.5.17********************************************** /#include <stdio.h> #define N 7void disp (void); int a[n]={5,0,7,1,12,11,9};/* sort function */void Insertionsort (void) {int j,p,temp;for (p=1;p<n;p++) {temp=a[p];//a[p] and left ordered series to compare/*j>0 guarantee not overflow, because when j=0 ah a[ J-1] illegal, with a[p] respectively and the value of the left to compare * * if A[P] small words are swapped position, */printf ("\ n" Sort process: "); for (j=p; j>0 && a[j-1]>temp;j--) {a[j]=a[j-1]; Disp (); } a[j]=temp;printf ("\ n \ nthe new round of sorting results: ");d ISP ();}} /* Output function */void disp (void) { int i;// printf ("\ n sort result: \ n"); printf ("\ n"); for (i=0;i<n;i++) {printf ("%d", a[i ]);p rintf (" ");}} int main (void) {Insertionsort (); disp (); return 0;}
Two. Algorithm can speak
1. Result output
2. Results analysis
Is the sequencing process and results for each round. For arrays of 7 numbers, a total of 6 rounds is required. Now I take out the third round to explain the insertion sort in detail.
The program has already lined up the first three numbers in the second round, and the third round compares a[3] (that is, the fourth number) to the previous number. 1 compared with 7, it is really less than 7, so a[3] is assigned to 7, then 1 continues to the left, 1:5 small, a[2] is assigned to 5, then 1 continues to the left, 1:0 large, loop the end. Assigns a value of a[1] to 1 (that is, temp).