使用 Swift3.0 實(shí)現(xiàn)“插入排序”算法

//需要 Swift 3.0 環(huán)境

//從小到大排序

var a = [6, 5, 4, 3, 2, 1]
print("a is \(a)")

//從第二個開始遍歷到最后一個
for j in 1...a.count-1 {
    //保留第 j 個的值,因?yàn)楹竺娴牟僮鲿薷臄?shù)組
    let n = a[j]
    print("now moving by \(n)")
    
    //記錄 j-1
    var i = j - 1
    //當(dāng)前面還有數(shù),并且前面的數(shù)比保留值大,則前后數(shù)交換位置
    while i >= 0 && a[i] > n {
        print("change \(a[i+1]) and \(a[i])")
        
        let temp = a[i+1]
        a[i+1] = a[i]
        a[i] = temp
        
        //繼續(xù)判斷前面的數(shù)
        i = i - 1
        
        print("j = \(j) and i = \(i) and a = \(a)")
    }
    print("")
}

//排序完成
print("sorted a is \(a)")
}

之后在Terminal運(yùn)行swift Numbers.swift即可看到輸出

a is [6, 5, 4, 3, 2, 1]
now moving by 5
change 5 and 6
j = 1 and i = -1 and a = [5, 6, 4, 3, 2, 1]

now moving by 4
change 4 and 6
j = 2 and i = 0 and a = [5, 4, 6, 3, 2, 1]
change 4 and 5
j = 2 and i = -1 and a = [4, 5, 6, 3, 2, 1]

now moving by 3
change 3 and 6
j = 3 and i = 1 and a = [4, 5, 3, 6, 2, 1]
change 3 and 5
j = 3 and i = 0 and a = [4, 3, 5, 6, 2, 1]
change 3 and 4
j = 3 and i = -1 and a = [3, 4, 5, 6, 2, 1]

now moving by 2
change 2 and 6
j = 4 and i = 2 and a = [3, 4, 5, 2, 6, 1]
change 2 and 5
j = 4 and i = 1 and a = [3, 4, 2, 5, 6, 1]
change 2 and 4
j = 4 and i = 0 and a = [3, 2, 4, 5, 6, 1]
change 2 and 3
j = 4 and i = -1 and a = [2, 3, 4, 5, 6, 1]

now moving by 1
change 1 and 6
j = 5 and i = 3 and a = [2, 3, 4, 5, 1, 6]
change 1 and 5
j = 5 and i = 2 and a = [2, 3, 4, 1, 5, 6]
change 1 and 4
j = 5 and i = 1 and a = [2, 3, 1, 4, 5, 6]
change 1 and 3
j = 5 and i = 0 and a = [2, 1, 3, 4, 5, 6]
change 1 and 2
j = 5 and i = -1 and a = [1, 2, 3, 4, 5, 6]

sorted a is [1, 2, 3, 4, 5, 6]

如果我們想要從大往小排序,只需要修改while i >= 0 && a[i] > n {...}while i >= 0 && a[i] < n {...}就可以了。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 背景 一年多以前我在知乎上答了有關(guān)LeetCode的問題, 分享了一些自己做題目的經(jīng)驗(yàn)。 張土汪:刷leetcod...
    土汪閱讀 12,921評論 0 33
  • 忘了上次這種內(nèi)心空蕩蕩的感覺是什么時候了,那種大浪拍打著礁巖卻發(fā)不出一點(diǎn)聲音。我已經(jīng)忘記看到那個的時候腦子里想的是...
    白菜沫君閱讀 386評論 0 1

友情鏈接更多精彩內(nèi)容