Skip to content

Commit 0718e87

Browse files
committed
Added more explanation to algorithm
1 parent 412df22 commit 0718e87

File tree

1 file changed

+24
-13
lines changed

1 file changed

+24
-13
lines changed

Mergesort/README.markdown

Lines changed: 24 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -46,29 +46,39 @@ Based off of the above example, here's what mergesort may look like:
4646
let array = [2, 1, 5, 4, 9]
4747

4848
func mergeSort(array: [Int]) -> [Int] {
49+
guard array.count > 1 else { return array } // 1
50+
let middleIndex = array.count / 2 // 2
4951

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
5353

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
5655

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
6257
}
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.
6369

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
6476
func merge(leftPile leftPile: [Int], rightPile: [Int]) -> [Int] {
6577
var leftIndex = 0
6678
var rightIndex = 0
6779

68-
// orderedPile will be the result of the merge
6980
var orderedPile = [Int]()
7081

71-
// insert
7282
while leftIndex < leftPile.count && rightIndex < rightPile.count {
7383
if leftPile[leftIndex] < rightPile[rightIndex] {
7484
orderedPile.append(leftPile[leftIndex])
@@ -96,4 +106,5 @@ func merge(leftPile leftPile: [Int], rightPile: [Int]) -> [Int] {
96106

97107
return orderedPile
98108
}
99-
```
109+
```
110+

0 commit comments

Comments
 (0)