//需要 Swift 3.0 环境
//从小到大排序
var a = [6, 5, 4, 3, 2, 1]
print("a is \(a)")
//从第二个开始遍历到最后一个
for j in 1...a.count-1 {
//保留第 j 个的值,因为后面的操作会修改数组
let n = a[j]
print("now moving by \(n)")
//记录 j-1
var i = j - 1
//当前面还有数,并且前面的数比保留值大,则前后数交换位置
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
//继续判断前面的数
i = i - 1
print("j = \(j) and i = \(i) and a = \(a)")
}
print("")
}
//排序完成
print("sorted a is \(a)")
}
之后在Terminal
运行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 {...}
就可以了。