《啊哈!算法》第 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..<count-1 {
//循环比较直到最后一个尚未归位的对象
for j in 0..<count-1-i {
if array[j].score < array[j+1].score {
swap(&array[j], &array[j+1])
}
}
}
for item in array {
print("\(item.name): \(item.score)")
}
冒泡排序的时间复杂度是 O(N2)
代码在 GitHub