插入排序是將一個數(shù)據(jù)插入到已經(jīng)排好序的有序數(shù)據(jù)中,從而得到一個新的、個數(shù)加一的有序數(shù)據(jù),算法適用于少量數(shù)據(jù)的排序,時間復雜度為O(n^2),比較穩(wěn)定的排序算法,實現(xiàn)起來也很簡單.
核心代碼:
<pre><code>` func sort(arr:inout [Int]) {
let count:Int = arr.count
for i in 1..<count { //注意起始位置
for j in (1...i).reversed() {
if arr[j] < arr[j-1] {
swap(&arr[j], &arr[j-1])
}
}
}
}
`</code></pre>
測試代碼:
<pre><code>var arr:[Int] = [9,7,6,5,1,2,0] let inserSort:InsertionSort = InsertionSort() inserSort.sort(arr: &arr) print("FlyElephant-插入排序---\(arr)")</code></pre>