The insertion sort is the most basic sort method, with a time complexity of O (N2).
The basic idea is to assume that a[0, ... j-1] is a sub-array that has been ordered, by comparing the a[j] with the preceding element, and inserting a[j] into the sorted sub-array.
The simple implementation of the insertion in the C language is sorted as follows:
1 /*Insert Sort C language implementation, time complexity O (n2)*/2 /*A is the array to sort, and Len is the length of the arrays*/3 voidInsert_sort (intA[],intLEN)4 {5 intI, J, key;6 for(j=1; j<len; J + +)7 {8Key =A[j];9i = j1;Ten while(i>0&& a[i]>key) One { Aa[i+1] =A[i]; ---i; - } thea[i+1] =key; - } -}
The test code is as follows:
1#include <stdio.h>2 3 #defineMAXSIZE 104 5 /*Insert Sort C language implementation, time complexity O (n2)*/6 /*A is the array to sort, and Len is the length of the arrays*/7 voidInsert_sort (intA[],intLEN)8 {9 intI, J, key;Ten for(j=1; j<len; J + +) One { AKey =A[j]; -i = j1; - while(i>0&& a[i]>key) the { -a[i+1] =A[i]; ---i; - } +a[i+1] =key; - } + } A at intMain () - { - intA[maxsize]; - inti; -printf"Please input the num:\n"); - for(i=0; i<maxsize; i++) in { -scanf"%d",&a[i]); to } +printf"before the sort:\n"); - for(i=0; i<maxsize; i++) the { *printf"%d", A[i]); $ }Panax Notoginsengprintf"\ n"); - the Insert_sort (A, MAXSIZE); + Aprintf"After the sort:\n"); the for(i=0; i<maxsize; i++) + { -printf"%d", A[i]); $ } $printf"\ n"); - -}
Insert sort of Base algorithm