冒泡排序,就是挨个遍历然后比较,发现不符合排序规则,进行交换,最终达到排序结果。
BubbleSort.swift
如下:
//冒泡排序
var a = [6, 5, 4, 3, 2, 1]
print("array is \(a)")
//遍历一遍数组
for i in 0...a.count-1 {
//挨个比较其他数字
for j in 0..<a.count-1-i {
print("i is \(i) and j is \(j)")
//如果右侧数字比自己小,则交换,让大的数字到右边
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
}
}
}
//排序结束
print("sorted array is \(a)")
Terminal
运行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]