Skip to content

Instantly share code, notes, and snippets.

@thexande
Last active August 15, 2018 21:06
Show Gist options
  • Save thexande/5122505b1f248af1430de204706b6c55 to your computer and use it in GitHub Desktop.
Save thexande/5122505b1f248af1430de204706b6c55 to your computer and use it in GitHub Desktop.
Merge Sort in Swift
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