Last active
August 29, 2015 14:17
-
-
Save MattFriedman/11a61c2a161375254087 to your computer and use it in GitHub Desktop.
This is a simple merge sort without optimizations written in the new Swift language for IOS
This file contains 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
func mergeSort(arr: [Int]) -> [Int]{ | |
func merge(left: [Int], right: [Int]) -> [Int] { | |
var m = 0 | |
var merged : [Int] = [] | |
var i = 0, j=0 | |
while i < left.count && j < right.count { | |
merged.insert( | |
left[i] < right[j] ? left[i++] : right[j++], atIndex: m++ | |
) | |
} | |
while i < left.count { | |
merged.insert(left[i++], atIndex: m++) | |
} | |
while j < right.count { | |
merged.insert(right[j++], atIndex: m++) | |
} | |
return merged | |
} // end merge() | |
if arr.count <= 1 { | |
return arr | |
} | |
let middle = Int( floor((Double(arr.count)/2))) | |
let left = mergeSort(Array(arr[0..<middle])) | |
let right = mergeSort(Array(arr[middle..<arr.count])) | |
return merge(left, right) | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment