Skip to content

Instantly share code, notes, and snippets.

@davidinga
Created August 22, 2019 21:00
Show Gist options
  • Select an option

  • Save davidinga/9dfa437e2a6b20b6fd0eee4cc6799936 to your computer and use it in GitHub Desktop.

Select an option

Save davidinga/9dfa437e2a6b20b6fd0eee4cc6799936 to your computer and use it in GitHub Desktop.
Recursive MergeSort implementation in Swift. Sorts an array of generic type, Element, when Element conforms to the Comparable protocol.
func mergeSort<Element>(array: inout [Element]) where Element: Comparable {
if array.count > 1 {
let mid = array.count / 2
var L = Array(array[..<mid])
var R = Array(array[mid...])
mergeSort(array: &L)
mergeSort(array: &R)
var i = 0, j = 0, k = 0
while i < L.count && j < R.count {
if L[i] < R[j] {
array[k] = L[i]
i += 1
} else {
array[k] = R[j]
j += 1
}
k += 1
}
while i < L.count {
array[k] = L[i]
i += 1
k += 1
}
while j < R.count {
array[k] = R[j]
j += 1
k += 1
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment