direct insertion sort

Basic idea: When inserting the ith (i > 1) element, the preceding V[0], V[1], ..., V[i - 1] are already sorted. At this time, use the sorting code of V[i] to compare with the sorting code order of V[i-1], V[i-2], ..., and find the insertion position to insert V[i]. Element moves backwards.

The following example illustrates:

Original data order: 21 , 25, 49, 25, 16, 8

The first pass: when i = 1, since 25 is greater than 21, the i-th element has been arranged: 21, 25, 49 , 25, 16, 8
Second pass: when i = 2, since 49 is greater than 25, the i-th element is already arranged: 21, 25, 49, 25, 16, 8
The third pass: when i = 3, since 25 is less than 49, 25 is inserted into the position of 49, and 49 needs to be moved backward: 21 , 25, 25 , 49 , 16, 8
Fourth pass: When i = 4, since 16 is smaller than all the previous elements, 16 is inserted into the frontmost position, that is, the position where 21 is inserted, and other elements are moved backward: 16, 21 , 25, 25 , 49 , 8
Fifth pass: When i = 5, since 8 is less than all the previous elements, 8 is inserted into the frontmost position, that is, the position where 16 is inserted, and other elements are moved backward: 8, 16, 21, 25, 25 , 49
完成直接插入排序:8、16、21、25、25、49
由直接插入排序过程可知,它的时间复杂度为 O(n的二次方);

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324605971&siteId=291194637