插入排序是將一個(gè)數(shù)據(jù)插入到已經(jīng)排好序的有序數(shù)據(jù)中软驰,從而得到一個(gè)新的呻逆、個(gè)數(shù)加一的有序數(shù)據(jù)簿废,算法適用于少量數(shù)據(jù)的排序,時(shí)間復(fù)雜度為O(n^2),比較穩(wěn)定的排序算法络它,實(shí)現(xiàn)起來(lái)也很簡(jiǎ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>
測(cè)試代碼:
<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>