Skip to content

Instantly share code, notes, and snippets.

@hirad
Created June 6, 2014 01:00
Show Gist options
  • Save hirad/9e97545abbcef7a76f97 to your computer and use it in GitHub Desktop.
Save hirad/9e97545abbcef7a76f97 to your computer and use it in GitHub Desktop.
Swift Merge Sort
let numbers = [9,29, 83, 19, 48, 65, 25, 30, 18, 1, 15, 84, 72, 63, 71]
func splitToSublists(list: Int[]) -> (Int[], Int[]) {
assert(list.count > 1, "List size must be greater than 1 before split")
let midIndex = (list.count / 2) as Int
var leftSublist: Int[] = Array(list[0..midIndex])
var rightSublist: Int[] = Array(list[midIndex..(list.count)])
return (leftSublist, rightSublist)
}
func merge(left: Int[], right: Int[]) -> Int[] {
var result: Int[] = Int[]()
var list1 = left
var list2 = right
while(list1.count > 0 && list2.count > 0)
{
if list1[0] <= list2[0] {
result += list1[0]
list1 = Array(list1[1..(list1.count)])
}
else
{
result += list2[0]
list2 = Array(list2[1..(list2.count)])
}
}
if list1.count > 0 {
result += list1
}
if list2.count > 0 {
result += list2
}
return result
}
func myMergeSort(list: Int[]) -> Int[] {
if list.count > 1 {
var (leftSublist, rightSublist) = splitToSublists(list)
leftSublist = myMergeSort(leftSublist)
rightSublist = myMergeSort(rightSublist)
return merge(leftSublist, rightSublist)
}
else
{
return list
}
}
var sorted = myMergeSort(numbers)
println(sorted)
// prints "[1, 9, 15, 18, 19, 25, 29, 30, 48, 63, 65, 71, 72, 83, 84]"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment