-
-
Save mxcl/d203fd6ceaa28264dc10 to your computer and use it in GitHub Desktop.
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
import Darwin //.C.stdlib | |
// updated for Swift 2.0 beta4 | |
private func merge<T: Comparable>(a: ArraySlice<T>, _ b: ArraySlice<T>, mergeInto acc: ArraySlice<T> = []) -> ArraySlice<T> { | |
guard let aF = a.first, bF = b.first else { | |
return acc + a + b | |
} | |
return aF < bF | |
? merge(dropFirst(a), b, mergeInto: acc + [aF]) | |
: merge(dropFirst(b), a, mergeInto: acc + [bF]) | |
} | |
private func divide<T: Comparable>(a: ArraySlice<T>) -> ArraySlice<T> { | |
let i = a.count / 2 | |
guard i > 0 else { return a } | |
let (left, right) = (a[0..<i], a[i..<a.count]) | |
return merge(divide(left), divide(right)) | |
} | |
public func mergesort<T: Comparable>(a: Array<T>) -> ArraySlice<T> { | |
return divide(ArraySlice(a)) | |
} | |
let unsorted = (1...100).map{_ in arc4random_uniform(200) } | |
let sorted = mergesort(unsorted) | |
print(sorted) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment