Skip to content

Commit ff9c766

Browse files
committed
added mergesort code
1 parent 63a19d5 commit ff9c766

File tree

1 file changed

+59
-1
lines changed

1 file changed

+59
-1
lines changed

Mergesort/README.markdown

Lines changed: 59 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -34,4 +34,62 @@ Given `[2]` `[1]` `[5]` `[4]` `[9]`, the first pass will result in `[1, 2]` and
3434

3535
The next pass will merge `[1, 2]` and `[4, 5]` together. This results in `[1, 2, 4, 5]`, with the `[9]` left out again since it's the odd one out.
3636

37-
Since you're left with 2 piles, `[9]` finally gets it's chance to merge, resulting in the sorted array `[1, 2, 4, 5, 9]`.
37+
Since you're left with 2 piles, `[9]` finally gets it's chance to merge, resulting in the sorted array `[1, 2, 4, 5, 9]`.
38+
39+
In code, it looks like this:
40+
41+
```
42+
let array = [2, 1, 5, 4, 9]
43+
44+
func mergeSort(array: [Int]) -> [Int] {
45+
46+
// base case - if the unsortedArray has less than 2 elements - aka 1 element, simply return, no need to split further
47+
if array.count < 2 { return array }
48+
let middleIndex = array.count / 2
49+
50+
// recursively split the left side of the array
51+
let leftArray = mergeSort(Array(array[0..<middleIndex]))
52+
53+
// recursively split the right side of the array
54+
let rightArray = mergeSort(Array(array[middleIndex..<array.count]))
55+
56+
// at this point, you should have n piles of arrays with a single element. Time to merge
57+
return merge(leftPile: leftArray, rightPile: rightArray)
58+
}
59+
60+
func merge(leftPile leftPile: [Int], rightPile: [Int]) -> [Int] {
61+
var leftIndex = 0
62+
var rightIndex = 0
63+
64+
// orderedPile will be the result of the merge
65+
var orderedPile = [Int]()
66+
67+
// insert
68+
while leftIndex < leftPile.count && rightIndex < rightPile.count {
69+
if leftPile[leftIndex] < rightPile[rightIndex] {
70+
orderedPile.append(leftPile[leftIndex])
71+
leftIndex += 1
72+
} else if leftPile[leftIndex] > rightPile[rightIndex] {
73+
orderedPile.append(rightPile[rightIndex])
74+
rightIndex += 1
75+
} else {
76+
orderedPile.append(leftPile[leftIndex])
77+
leftIndex += 1
78+
orderedPile.append(rightPile[rightIndex])
79+
rightIndex += 1
80+
}
81+
}
82+
83+
while leftIndex < leftPile.count {
84+
orderedPile.append(leftPile[leftIndex])
85+
leftIndex += 1
86+
}
87+
88+
while rightIndex < rightPile.count {
89+
orderedPile.append(rightPile[rightIndex])
90+
rightIndex += 1
91+
}
92+
93+
return orderedPile
94+
}
95+
```

0 commit comments

Comments
 (0)