@@ -46,29 +46,39 @@ Based off of the above example, here's what mergesort may look like:
46
46
let array = [2 , 1 , 5 , 4 , 9 ]
47
47
48
48
func mergeSort (array : [Int ]) -> [Int ] {
49
+ guard array.count > 1 else { return array } // 1
50
+ let middleIndex = array.count / 2 // 2
49
51
50
- // base case - if the unsortedArray has less than 2 elements - aka 1 element, simply return, no need to split further
51
- if array.count < 2 { return array }
52
- let middleIndex = array.count / 2
52
+ let leftArray = mergeSort (Array (array[0 ..< middleIndex])) // 3
53
53
54
- // recursively split the left side of the array
55
- let leftArray = mergeSort (Array (array[0 ..< middleIndex]))
54
+ let rightArray = mergeSort (Array (array[middleIndex..< array.count ])) // 4
56
55
57
- // recursively split the right side of the array
58
- let rightArray = mergeSort (Array (array[middleIndex..< array.count ]))
59
-
60
- // at this point, you should have n piles of arrays with a single element. Time to merge
61
- return merge (leftPile : leftArray, rightPile : rightArray)
56
+ return merge (leftPile : leftArray, rightPile : rightArray) // 5
62
57
}
58
+ ```
59
+
60
+ A step-by-step explanation of how the code works:
61
+
62
+ 1 . If the array is empty or only contains a single element, there's no way to split it into smaller pieces. You'll just return the array.
63
+
64
+ 2 . Find the middle index.
65
+
66
+ 3 . Using the middle index from the previous step, recursively split the left side of the resulting arrays.
67
+
68
+ 4 . Using the middle index, recursively split the right side of the resulting arrays.
63
69
70
+ 5 . Finally, merge all the values together, making sure that it's always sorted
71
+
72
+
73
+ Here's the merging algorithm:
74
+
75
+ ``` swift
64
76
func merge (leftPile leftPile : [Int ], rightPile : [Int ]) -> [Int ] {
65
77
var leftIndex = 0
66
78
var rightIndex = 0
67
79
68
- // orderedPile will be the result of the merge
69
80
var orderedPile = [Int ]()
70
81
71
- // insert
72
82
while leftIndex < leftPile.count && rightIndex < rightPile.count {
73
83
if leftPile[leftIndex] < rightPile[rightIndex] {
74
84
orderedPile.append (leftPile[leftIndex])
@@ -96,4 +106,5 @@ func merge(leftPile leftPile: [Int], rightPile: [Int]) -> [Int] {
96
106
97
107
return orderedPile
98
108
}
99
- ```
109
+ ```
110
+
0 commit comments