Last active
August 15, 2018 21:06
-
-
Save thexande/5122505b1f248af1430de204706b6c55 to your computer and use it in GitHub Desktop.
Merge Sort in Swift
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 sort(_ array: [Int]) -> [Int] { | |
guard array.count > 1 else { | |
return array | |
} | |
let left = Array(array[0..<array.count / 2]) | |
let right = Array(array[array.count/2..<array.count]) | |
return merge(sort(left), sort(right)) | |
} | |
func merge(_ arrayOne: [Int], _ arrayTwo: [Int]) -> [Int] { | |
var merged: [Int] = [] | |
var left = arrayOne | |
var right = arrayTwo | |
while left.count > 0 && right.count > 0 { | |
if left.first! < right.first! { | |
merged.append(left.removeFirst()) | |
} else { | |
merged.append(right.removeFirst()) | |
} | |
} | |
return merged + left + right | |
} | |
print(sort([1, 5, 2, 4, 6])) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment