Aha! Algorithms - Bubble Sort

《啊哈!算法》第 1 章第 2 节,冒泡排序的 Swift 实现

问题

给学生成绩排序,打印排序后的名字(和成绩)

解决

依次比较相邻的两个学生分数的大小,把低分的放到后面,直到最后一个尚未归位的学生

struct Student {
    let name: String
    let score: Int
}

var array: [Student] = [Student(name: "huhu", score: 5),
                        Student(name: "haha", score: 3),
                        Student(name: "xixi", score: 5),
                        Student(name: "hehe", score: 2),
                        Student(name: "momo", score: 8)]

let count = array.count

//N 个对象排序,只需要循环 N-1 遍
for i in 0..

冒泡排序的时间复杂度是 O(N2)

代码在 GitHub

你可能感兴趣的:(Aha! Algorithms - Bubble Sort)