Last active
February 8, 2016 17:29
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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