Insert Sort (insertion sort) is a simple and intuitive sorting algorithm. It works by constructing an ordered sequence, for unsorted data, to scan from backward forward in the sorted sequence, to find the appropriate position and insert it. The insertion sort is implemented on an implementation, usually in the order of In-place (that is, the ordering of extra space using only O (1), so that in the backward-forward scanning process, the ordered elements need to be moved back and forth gradually, providing the insertion space for the newest elements. (Excerpt from Wikipedia)
The simple point of understanding is this: imagine you are holding a cluttered poker, and then you will naturally be the hands of the cards to replace the position, so that the order is right? The following picture is an example of the introduction of algorithms.
So the insertion sort is divided into two areas, one is already lined up, and the other piece is not yet lined up; as long as you are not in the order of the block from the element inserted into the order of the block, then wait until the order is not yet the elements of the element has not, it is already lined up.
The idea is simple, the following gives my code (the first three sentences of the second for loop of the sort function are to be able to visually output the sorting process):
1 /*2 * This is my own writing of the insertion sort, as in the book of Ideas,3 * are inserted, but the implementation of the code is different. 4 */5#include <stdio.h>6#include <stdlib.h>7#include <time.h>8 #defineM 109 Ten voidInsertion_sort (int*p) One { A intI, J, TMP; - for(i =1; i < M; i++) - for(j =0; J < I; J + +) the { -printf"%2d", * (P + j));/*Output*/ - if(j +1= = i)/*Output*/ -printf"\ n");/*Output*/ + if(* (P + j) > * (P +i)) - { +TMP = * (P +j); A* (P + j) = * (P +i); at* (p + i) =tmp; - - } - } - } - in intMainvoid) - { to inti; + intA[m] = {0}; - the //randomly generate 10 double-digit numbers *Srand (Time (0)); $ for(i =0; i < M; i++)Panax NotoginsengA[i] = rand ()% -; - theprintf"not sorted ... \ n" ); + for(i =0; i < M; i++) Aprintf"%2d", A[i]); theprintf"\ n" ); +printf"\ n Sort in ... \ n"); - Insertion_sort (a); $ $ -printf"\ n already sorted ... \ n" ); - for(i =0; i < M; i++) theprintf"%2d", A[i]); - Wuyiprintf"\ n" ); the - return 0; Wu -}
View Code
Here is the result of the run:
The complexity of Time is O (n^2), because there are two loops.
An implementation of insertion sorting algorithm