标签:bre swa swift count else out com 版本 let
插入排序(只记录代码不作详细分析)
插入排序将输入的元素一个个插入到已排序的队列里,对比是由后往前
代码:
func insertSort<Elem: Comparable>(_ arr: inout [Elem]) {
for i in 1...arr.count-1 {
let tmp = arr[i]
for j in (0...i-1).reversed() {
if (j > 0 && arr[j] > tmp) {
arr[j + 1] = arr[j]
} else {
arr[j + 1] = tmp
break
}
}
}
}
冒泡排序:
func bubbleSort<Elem: Comparable>(_ arr: inout [Elem]) {
func swap(_ a: inout Elem, _ b: inout Elem) {
let tmp = a
a = b
b = tmp
}
for i in (1...arr.count-1).reversed() {
for j in 0...i-1 {
if arr[j] > arr[j+1] {
swap(&arr[j], &arr[j+1])
}
}
}
}
标签:bre swa swift count else out com 版本 let
原文地址:http://www.cnblogs.com/naturelight/p/6362791.html