Skip to content

Instantly share code, notes, and snippets.

@proxpero
Last active February 8, 2016 17:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save proxpero/ed8fa8199c6f1eff637f to your computer and use it in GitHub Desktop.
Save proxpero/ed8fa8199c6f1eff637f to your computer and use it in GitHub Desktop.
A simple implementation of Merge Sort in Swift as an extension on Array
// Swift 2.1
extension Array where Element : Comparable {
private func merge(var left: Array<Element>, var _ right: Array<Element>) -> Array<Element> {
var result: Array<Element> = []
while !left.isEmpty && !right.isEmpty {
if left[startIndex] <= right[startIndex] {
result.append(left.removeFirst())
} else {
result.append(right.removeFirst())
}
}
if !left.isEmpty {
result.appendContentsOf(left)
}
if !right.isEmpty {
result.appendContentsOf(right)
}
return result
}
public func mergeSort() -> Array<Element> {
guard count > 1 else { return self }
let mid = count / 2
return merge(
Array(self[startIndex..<mid]).mergeSort(),
Array(self[mid ..< endIndex]).mergeSort()
)
}
}
func testMergeSort() {
let integers = [2, 10, 5, 3, 8, 4, 7, 9, 6, 1]
// test that merge sort returns a sorted array.
assert(integers.mergeSort() == [1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
print("merge sort tests passed")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment