Last active
August 29, 2015 14:02
-
-
Save hodgesmr/daa36f308d5880e5f8ff to your computer and use it in GitHub Desktop.
An implementation of Merge Sort in Swift
This file contains hidden or 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(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