# Swift 算法实战之路：排序

## 基本概念

``````func mergeSort(array: [Int]) -> [Int] {
var helper = Array(count: array.count, repeatedValue: 0)
var array = array
mergeSort(&array, &helper, 0, array.count - 1)
return array
}

func mergeSort(inout array: [Int], inout _ helper: [Int], _ low: Int, _ high: Int) {
guard low < high else {
return
}

let middle = (high - low) / 2 + low
mergeSort(&array, &helper, low, middle)
mergeSort(&array, &helper, middle + 1, high)
merge(&array, &helper, low, middle, high)
}

func merge(inout array: [Int], inout _ helper: [Int], _ low: Int, _ middle: Int, _ high: Int) {
// copy both halves into a helper array
for i in low ... high {
helper[i] = array[i]
}

var helperLeft = low
var helperRight = middle + 1
var current = low

// iterate through helper array and copy the right one to original array
while helperLeft <= middle="" &&="" helperright="" <="high" {="" if="" helper[helperleft]="" array[current]="helper[helperLeft]" helperleft="" +="1" }="" else="" current="" handle="" the="" rest="" guard="" -="">= 0 else {
return
}
for i in 0 ... middle - helperLeft {
array[current + i] = helper[helperLeft + i]
}
}复制代码``````

``````// 原数组
[[2, 1], [1,3], [1,4]]

// 排序算法一
[[1,3], [1,4], [2, 1]]
// 排序算法二
[[1,4], [1,3], [2, 1]]复制代码``````

Swift中，排序的使用如下：

``````// 以升序排列为例，原数组可改变
array.sortInPlace(<) 以降序排列为例，原数组不可改变="" newarray="array.sort(">)

// 字典键值排序示例
let keys = Array(map.keys)
let sortedKeys = keys.sort() {
let value1 = map[\$0]
let value2 = map[\$1]
return value1 > value2
}复制代码``````

## 排序实战

``````public class MeetingTime {
public var start: Int
public var end: Int
public init(_ start: Int, _ end: Int) {
self.start = start
self.end = end
}
}复制代码``````

``func merge(meetingTimes: [MeetingTime]) -> [MeetingTime] {}复制代码``

``````meetingTimes.sortInPlace() {
if \$0.start != \$1.start {
return \$0.start < \$1.start
} else {
return \$0.end < \$1.end
}
}复制代码``````

``````func merge(meetingTimes: [MeetingTime]) -> [MeetingTime] {
// 处理特殊情况
guard meetingTimes.count > 1 else {
return meetingTimes
}

// 排序
var meetingTimes = meetingTimes.sort() {
if \$0.start != \$1.start {
return \$0.start < \$1.start
} else {
return \$0.end < \$1.end
}
}

// 新建结果数组
var res = [MeetingTime]()
res.append(meetingTimes[0])

// 遍历排序后的原数组，并与结果数组归并
for i in 1.. last.end {
res.append(current)
} else {
last.end = max(last.end, current.end)
}
}

return res
}复制代码``````