(1) Principle:
The first element is regarded as sorted, and the second element is stored in a temporary variable key,
If the first element is greater than the second element, move the first element to the second element;
In this way, the key can be inserted at the original position of the first element.
The insert method, as its name implies, is to first locate a location and then insert it in.
(2) Example:
(3) c ++ implementation
# Include <iostream> # include <cstdlib> # include <cstdio> using namespace STD; // int A [100]; // use insert_sort (A, 100 ); not insert_sort (A, 99) // void insert_sort (int * a, int N) {// assert (! = NULL & n> 0); For (Int J = 1; j <n; ++ J) {int key = A [J]; // temporarily Save the element to be inserted. Int I = J-1; while (I> = 0 & A [I]> key) // there must be a position to insert. The purpose of the loop is to move all elements smaller than J in the following table as long as they are larger than a [J. {A [I + 1] = A [I]; -- I;} A [I + 1] = key;} void print (int * a, int N) {for (INT I = 0; I <n; ++ I) {printf ("% 2D", a [I]) ;}printf ("\ n ");} int main () {int A [] = {, 99,-,}; insert_sort (A, sizeof (a)/sizeof (* )); print (A, sizeof (a)/sizeof (* A); Return 0 ;}
References:
[1] http://www.algolist.net/Algorithms/Sorting/Insertion_sort
[2] http://baike.baidu.com/view/396887.htm
[3] http://www.personal.kent.edu /~ Rmuhamma/algorithms/myalgorithms/sorting/insertionsort.htm
[4] http://video.sina.com.cn/v/ B /80012377-1642346981.html