-
Notifications
You must be signed in to change notification settings - Fork 98
/
mergeSort.swift
47 lines (41 loc) · 1.06 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
// a function that merges two arrys
func merge(_ array_1: inout [Int], _ low: Int, _ mid: Int, _ high: Int) {
var i = low
var j = mid + 1
var k = 0
var array_2: [Int] = [Int](repeating: 0, count: high - low + 1)
while i <= mid && j <= high {
if array_1[i] <= array_1[j] {
array_2[k] = array_1[i]
k += 1
i += 1
}
else {
array_2[k] = array_1[j]
k += 1
j += 1
}
}
while i <= mid {
array_2[k] = array_1[i]
k += 1
i += 1
}
while j <= high {
array_2[k] = array_1[j]
k += 1
j += 1
}
for i in low...high {
array_1[i] = array_2[i - low]
}
}
// the recursive sorting algorithm that divides the array, sorts the two halves and merges them
func sort(_ array: inout [Int], _ low: Int, _ high: Int) {
if low < high {
let mid = (low + high) / 2
sort(&array, low, mid)
sort(&array, mid + 1, high)
merge(&array, low, mid, high)
}
}