<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.1/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script>
# Insert Sort - 插入排序
--------
#### 問題
用插入排序對長度為$$ n $$的無序序列$$ s $$進行排序。
#### 解法
本問題對無序序列$$ s $$進行升序排序,排序后$$ s $$是從小到大的。
將長度為$$ n $$的序列$$ s $$分為左右兩個部分$$ left $$和$$ right $$,$$ left $$是已序的,范圍為$$ s[0,k] $$,$$ right $$是未序的,范圍為$$ s[k+1,n-1] $$,其中$$ 0 \le k \lt n $$。對$$ right $$中最左邊的元素$$ x = s[k+1] $$,在$$ left $$部分中找到一個位置$$ i $$,滿足$$ s[i-1] \le x \le s[i] $$,也就是說$$ x $$可以夾在$$ s[i-1] $$和$$ s[i] $$之間。為了滿足$$ left $$的有序性,將$$ left $$中$$ s[i,k] $$部分的元素向右移動一個位置到$$ s[i+1,k+1] $$,將$$ x $$放置在原$$ s[i] $$的位置即可。
例如下圖中,$$ left $$部分為$$ s[0,5] $$,$$ right $$部分為$$ s[6,n-1] $$,$$ right $$最左邊的首部元素$$ x = s[6] = 41 $$,在$$ left $$部分中合適的插入位置為$$ i = 3 $$($$ s[2] \le x \le s[3] $$)。

將$$ s[3,5] $$向右移動一位到$$ s[4,6] $$,將原$$ x $$移動到$$ s[3] $$,就完成了一次插入。

對于長度為$$ n $$的數組$$ s $$,將$$ left $$初始化為$$ s[0,0] $$,$$ right $$初始化為$$ s[1,n-1] $$。重復上面的插入操作,直到$$ right $$為空,這時$$ left $$部分即為已序的結果,算法結束。對長度為$$ n $$的序列$$ s $$,每一輪將$$ right $$中一個元素插入$$ left $$中的時間為$$ O(n) $$,總共需要$$ n $$輪操作,該算法的時間復雜度為$$ O(n^2) $$。
--------
#### 源碼
[InsertSort.h](https://github.com/linrongbin16/Way-to-Algorithm/blob/master/src/Sort/InsertSort.h)
[InsertSort.cpp](https://github.com/linrongbin16/Way-to-Algorithm/blob/master/src/Sort/InsertSort.cpp)
#### 測試
[InsertSortTest.cpp](https://github.com/linrongbin16/Way-to-Algorithm/blob/master/src/Sort/InsertSortTest.cpp)
- Content 目錄
- Preface 前言
- Chapter-1 Sort 第1章 排序
- InsertSort 插入排序
- BubbleSort 冒泡排序
- QuickSort 快速排序
- MergeSort 歸并排序
- Chapter-2 Search 第2章 搜索
- BinarySearch 二分查找法(折半查找法)
- BruteForce 暴力枚舉
- Recursion 遞歸
- BreadthFirstSearch 廣度優先搜索
- BidirectionalBreadthSearch 雙向廣度搜索
- AStarSearch A*搜索
- DancingLink 舞蹈鏈
- Chapter-3 DataStructure 第3章 數據結構
- DisjointSet 并查集
- PrefixTree(TrieTree) 前綴樹
- LeftistTree(LeftistHeap) 左偏樹(左偏堆)
- SegmentTree 線段樹
- FenwickTree(BinaryIndexedTree) 樹狀數組
- BinarySearchTree 二叉查找樹
- AVLTree AVL平衡樹
- RedBlackTree 紅黑樹
- Chapter-4 DynamicProgramming 第4章 動態規劃
- Chapter-5 GraphTheory 第5章 圖論
- Chapter-6 Calculation 第6章 計算
- LargeNumber 大數字
- Exponentiation 求冪運算
- Chapter-7 CombinatorialMathematics 第7章 組合數學
- FullPermutation 全排列
- UniqueFullPermutation 唯一的全排列
- Combination 組合
- DuplicableCombination (元素)可重復的組合
- Subset 子集
- UniqueSubset 唯一的子集
- Permutation 排列
- PermutationGroup 置換群
- Catalan 卡特蘭數
- Chapter-8 NumberTheory 第8章 數論
- Sieve 篩選算法
- Euclid 歐幾里得
- EuclidExtension 歐幾里得擴展
- ModularLinearEquation 模線性方程
- ChineseRemainerTheorem 中國剩余定理
- ModularExponentiation 模冪運算
- Chapter-9 LinearAlgebra 第9章 線性代數
- Chapter-10 AnalyticGeometry 第10章 解析幾何
- Chapter-11 TextMatch 第11章 文本匹配
- SimpleMatch 簡單匹配
- AhoCorasickAutomata AC自動機
- KnuthMorrisPratt KMP匹配算法
- RabinKarp RabinKarp算法
- BoyerMoore BoyerMoore算法
- Chapter-12 GameTheory 第12章 博弈論
- BashGame 巴什博弈
- WythoffGame 威佐夫博弈
- NimGame 尼姆博弈