Skip to content

Instantly share code, notes, and snippets.

@hodgesmr
Last active August 29, 2015 14:02
Show Gist options
  • Save hodgesmr/daa36f308d5880e5f8ff to your computer and use it in GitHub Desktop.
Save hodgesmr/daa36f308d5880e5f8ff to your computer and use it in GitHub Desktop.
An implementation of Merge Sort in Swift
func mergeSort(numbers: Int[], left: Int, right: Int) {
if right > left {
let splitIndex = (left + right) / 2
mergeSort(numbers, left, splitIndex)
mergeSort(numbers, splitIndex+1, right)
var result = Int[]()
var nextLeft = left
var nextRight = splitIndex + 1
while nextLeft <= splitIndex && nextRight <= right {
if numbers[nextLeft] < numbers[nextRight] {
result.append(numbers[nextLeft])
nextLeft++
}
else {
result.append(numbers[nextRight])
nextRight++
}
}
for i in nextLeft...splitIndex {
result.append(numbers[i])
}
for i in nextRight...right {
result.append(numbers[i])
}
for i in 0..result.count {
numbers[left + i] = result[i]
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment