Skip to content

Commit dd9097d

Browse files
committed
More explanations
1 parent 0718e87 commit dd9097d

File tree

1 file changed

+13
-2
lines changed

1 file changed

+13
-2
lines changed

Mergesort/README.markdown

Lines changed: 13 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -43,8 +43,6 @@ Since you're left with 2 piles, `[9]` finally gets it's chance to merge, resulti
4343
Based off of the above example, here's what mergesort may look like:
4444

4545
```swift
46-
let array = [2, 1, 5, 4, 9]
47-
4846
func mergeSort(array: [Int]) -> [Int] {
4947
guard array.count > 1 else { return array } // 1
5048
let middleIndex = array.count / 2 // 2
@@ -74,11 +72,14 @@ Here's the merging algorithm:
7472

7573
```swift
7674
func merge(leftPile leftPile: [Int], rightPile: [Int]) -> [Int] {
75+
// 1
7776
var leftIndex = 0
7877
var rightIndex = 0
7978

79+
// 2
8080
var orderedPile = [Int]()
8181

82+
// 3
8283
while leftIndex < leftPile.count && rightIndex < rightPile.count {
8384
if leftPile[leftIndex] < rightPile[rightIndex] {
8485
orderedPile.append(leftPile[leftIndex])
@@ -94,6 +95,7 @@ func merge(leftPile leftPile: [Int], rightPile: [Int]) -> [Int] {
9495
}
9596
}
9697

98+
// 4
9799
while leftIndex < leftPile.count {
98100
orderedPile.append(leftPile[leftIndex])
99101
leftIndex += 1
@@ -108,3 +110,12 @@ func merge(leftPile leftPile: [Int], rightPile: [Int]) -> [Int] {
108110
}
109111
```
110112

113+
This method is quite straightforward:
114+
115+
1. You need 2 indexes to keep track of your progress for the two arrays while merging.
116+
117+
2. This is the merged array. It's empty right now, but you'll build it up in subsequent steps by appending elements from the other arrays.
118+
119+
3. This while loop will compare the elements from the left and right sides to make sure that the result stays in order.
120+
121+
4. If control exits from the previous while loop, it means that either `leftPile` or `rightPile` has it's contents completely merged into the `orderedPile`. At this point, you no longer need to do comparisons. Just append the rest of the contents of the other array until there's no more to append.

0 commit comments

Comments
 (0)