• 基本概念
• 排序实战

# 基本概念

``````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] <= helper[helperRight] {
array[current] = helper[helperLeft]
helperLeft += 1
} else {
array[current] = helper[helperRight]
helperRight += 1
}
current += 1
}

// handle the rest
guard middle - helperLeft >= 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.sort

// 以降序排列为例，原数组不可改变
newArray = array.sorted(by: >)

// 字典键值排序示例
let keys = Array(map.keys)
let sortedKeys = keys.sorted() {
return map[\$0]! > map[\$1]!
}
``````

# 排序实战

``````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..<meetingTimes.count {
let last = res[res.count - 1]
let current = meetingTimes[i]
if current.start > last.end {
res.append(current)
} else {
last.end = max(last.end, current.end)
}
}

return res
}
``````