Brief
Description insertion sort algorithm (Insertion-Sort) is a straightforward sorting algorithm. It works by constructing an ordered sequence, for unsorted data, scanning in the sorted sequence from back to front, and find the corresponding insertion positions. In the realization of insertion sort, sort commonly used in-place (i.e., only need to use the sort of extra space O (1)), and therefore in the forward scan from the process, the need to repeatedly sorted elements gradually move rearward position , the latest element inserted into the space provided.
Moving map presentation
See FIG moving below demonstrates, can be easily understood that the contents of the above.
(Algorithm in FIG movable from reference, please refer to the detailed down)
Code
1 / * 2 * insertion sort . 3 * @param Array . 4 * @return . 5 * / . 6 public static int [] InsertionSort ( int [] Array) { . 7 int len; . 8 // array base case can be directly returned 9 IF (Array == null || (= len be array.length) == == 0 || len. 1 ) { 10 return Array; . 11 } 12 is int Current; 13 is for ( int I = 0; I <len -. 1; i ++) { 14 // first the default number of sorted, starting from the second number 15 Current Array = [I +. 1 ]; 16 // a front lower subscript number . 17 int preIdx = I; 18 is . 19 // get the current sorted one by one before the sequence number of the previous comparison, 20 // if the current data is larger than the comparison, the number of put moved back one step 21 is the while (preIdx> = 0 && current < Array [preIdx]) { 22 is Array [preIdx +. 1] = Array [preIdx]; 23 is preIdx-- ; 24 } 25 // the while loop to find out the location of the description 26 is Array [preIdx +. 1] = Current; 27 } 28 return array; 29 }
Analysis of Algorithms
Best case: T (n-) = O (n-) worst case: (n-T (n-) = O 2 ) Average where: T (n-) = O (n- 2 )
Reference material
1 https: //www.cnblogs.com/guoyaohua/p/8600214.html