Swift3.0 冒泡排序

冒泡排序,就是挨個(gè)遍歷然后比較,發(fā)現(xiàn)不符合排序規(guī)則,進(jìn)行交換,最終達(dá)到排序結(jié)果。
BubbleSort.swift如下:

//冒泡排序

var a = [6, 5, 4, 3, 2, 1]

print("array is \(a)")

//遍歷一遍數(shù)組
for i in 0...a.count-1 {
    //挨個(gè)比較其他數(shù)字
    for j in 0..<a.count-1-i {
        print("i is \(i) and j is \(j)")
        
        //如果右側(cè)數(shù)字比自己小,則交換,讓大的數(shù)字到右邊
        if a[j] > a[j+1] {
            print("change \(a[j]) and \(a[j+1])")
            
            let temp = a[j+1]
            a[j+1] = a[j]
            a[j] = temp
        }
    }
}

//排序結(jié)束
print("sorted array is \(a)")

Terminal運(yùn)行swift BubbleSort.swift可見:

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

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

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