插入排序步骤
前面文章分享了两种排序算法:冒泡排序和选择排序。虽然它们的效率都是O(N2),但其实选择排序比冒泡排序快一倍。现在来学第三种排序算法------插入排序。你会发现,顾及最坏情况以外的场景将是多么有用。
插入排序包括以下步骤。
(1) 在第一轮里,暂时将索引1(第2格)的值移走,并用一个临时变量来保存它。这使得该索引处留下一个空隙,因为它不包含值。

在之后的轮回,我们会移走后面索引的值。
(2) 接着便是平移阶段,我们会拿空隙左侧的每一个值与临时变量的值进行比较。

如果空隙左侧的值大于临时变量的值,则将该值右移一格。

随着值右移,空隙会左移。如果遇到比临时变量小的值,或者空隙已经到了数组的最左端,就结束平移阶段。
(3) 将临时移走的值插入当前空隙。

(4) 重复第(1)至(3)步,直至数组完全有序。
插入排序实战
下面尝试对[4, 2, 7, 1, 3]数组运用插入排序。第1轮先从索引1开始,其值为2。

准备工作:暂时移走2,并将其保存在变量temp_value中。图中被移到数组上方的就是temp_value。

第1步:比较4与temp_value中的2。

第2步:因为4大于2,所以把4右移。

于是空隙移到了数组最左端,没有其他值可以比较了。
第3步:将temp_value插回数组,完成第一轮。

开始第2轮。
准备工作:暂时移走索引2的值,并保存到temp_value中。于是temp_value等于7。

第4步:比较4与temp_value。

4小于7,所以无须平移。因为遇到了小于temp_value的值,所以平移阶段结束。
第5步:将temp_value插回到空隙中,结束第2轮。

开始第3轮。
准备工作:暂时移走1,并将其保存到temp_value中。

第6步:比较7与temp_value。

第7步:7大于1,于是将7右移。

第8步:比较4与temp_value。

第9步:4大于1,于是也要将4右移。

第10步:比较2与temp_value。

第11步:2比较大,所以将2右移。

第12步:空隙到了数组最左端,因此我们将temp_value插进去,结束这一轮。

开始第4轮。
准备工作:暂时移走索引4的值3,保存到temp_value中。

第13步:比较7和temp_value。

第14步:7更大,于是将7右移。

第15步:比较4与temp_value。

第16步:4大于3,所以将4右移。

第17步:比较2与temp_value。2小于3,于是平移阶段完成。

第18步:把temp_value插回到空隙。

至此整个数组都排好序了。
