-
-
Notifications
You must be signed in to change notification settings - Fork 137
/
Copy pathMergeSort.swift
69 lines (61 loc) · 1.76 KB
/
MergeSort.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
import Foundation
extension Array where Element: Comparable {
mutating func mergeSort(by comparison: (Element, Element) -> Bool) {
guard self.count > 1 else {
return
}
_mergeSort(from: 0, to: count - 1, by: comparison)
}
mutating private func _mergeSort(
from left: Int,
to right: Int,
by comparison: (Element, Element) -> Bool
) {
if left < right {
let mid = left + (right - left) / 2
_mergeSort(from: 0, to: mid, by: comparison)
_mergeSort(from: mid + 1, to: right, by: comparison)
_merge(from: left, mid: mid, to: right, by: comparison)
}
}
mutating private func _merge(
from left: Int,
mid: Int,
to right: Int,
by comparison: (Element, Element) -> Bool
) {
var copy = [Element](repeating: self[left], count: right - left + 1)
var (leftStartIndex, rightStartIndex, currentIndex) = (left, mid + 1, 0)
for _ in left ... right {
if leftStartIndex > mid {
copy[currentIndex] = self[rightStartIndex]
rightStartIndex += 1
} else if rightStartIndex > right {
copy[currentIndex] = self[leftStartIndex]
leftStartIndex += 1
} else if comparison(self[leftStartIndex], self[rightStartIndex]) {
copy[currentIndex] = self[leftStartIndex]
leftStartIndex += 1
} else {
copy[currentIndex] = self[rightStartIndex]
rightStartIndex += 1
}
currentIndex += 1
}
leftStartIndex = left
for i in copy.indices {
self[leftStartIndex] = copy[i]
leftStartIndex += 1
}
}
func mergeSorted(by comparison: (Element, Element) -> Bool) -> Array {
var copy = self
copy.mergeSort(by: comparison)
return copy
}
}
// The code below can be used for testing
// var numberList = [15, 2, 23, 11, 3, 9]
// debugPrint(numberList.mergeSorted(by: >))
// numberList.mergeSort(by: <)
// debugPrint(numberList)