Skip to content

Commit

Permalink
Merge pull request TheAlgorithms#24 from codersanjeev/master
Browse files Browse the repository at this point in the history
  • Loading branch information
carloshmartins authored Jul 18, 2021
2 parents 915684d + 1775e91 commit b9e3107
Show file tree
Hide file tree
Showing 2 changed files with 70 additions and 0 deletions.
1 change: 1 addition & 0 deletions DIRECTORY.md
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@
* [Insertionsort](https://github.com/TheAlgorithms/Swift/blob/master/sorts/InsertionSort.swift)
* [Quicksort](https://github.com/TheAlgorithms/Swift/blob/master/sorts/QuickSort.swift)
* [Selectionsort](https://github.com/TheAlgorithms/Swift/blob/master/sorts/SelectionSort.swift)
* [MergeSort](https://github.com/TheAlgorithms/Swift/blob/master/sorts/MergeSort.swift)

## Trees
* [Tree](https://github.com/TheAlgorithms/Swift/blob/master/trees/tree.swift)
69 changes: 69 additions & 0 deletions sorts/MergeSort.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@

import Foundation

extension Array where Element: Comparable {

mutating func mergeSort(by comparison: (Element, Element) -> Bool) {
guard self.count > 1 else {
return
}
_mergeSort(from: 0, to: count - 1, by: comparison)
}

mutating private func _mergeSort(
from left: Int,
to right: Int,
by comparison: (Element, Element) -> Bool
) {
if left < right {
let mid = left + (right - left) / 2
_mergeSort(from: 0, to: mid, by: comparison)
_mergeSort(from: mid + 1, to: right, by: comparison)
_merge(from: left, mid: mid, to: right, by: comparison)
}
}

mutating private func _merge(
from left: Int,
mid: Int,
to right: Int,
by comparison: (Element, Element) -> Bool
) {
var copy = [Element](repeating: self[left], count: right - left + 1)
var (leftStartIndex, rightStartIndex, currentIndex) = (left, mid + 1, 0)
for _ in left ... right {
if leftStartIndex > mid {
copy[currentIndex] = self[rightStartIndex]
rightStartIndex += 1
} else if rightStartIndex > right {
copy[currentIndex] = self[leftStartIndex]
leftStartIndex += 1
} else if comparison(self[leftStartIndex], self[rightStartIndex]) {
copy[currentIndex] = self[leftStartIndex]
leftStartIndex += 1
} else {
copy[currentIndex] = self[rightStartIndex]
rightStartIndex += 1
}
currentIndex += 1
}
leftStartIndex = left
for i in copy.indices {
self[leftStartIndex] = copy[i]
leftStartIndex += 1
}
}

func mergeSorted(by comparison: (Element, Element) -> Bool) -> Array {
var copy = self
copy.mergeSort(by: comparison)
return copy
}

}

// The code below can be used for testing
// var numberList = [15, 2, 23, 11, 3, 9]
// debugPrint(numberList.mergeSorted(by: >))
// numberList.mergeSort(by: <)
// debugPrint(numberList)

0 comments on commit b9e3107

Please sign in to comment.