Skip to content

Instantly share code, notes, and snippets.

@freddi-kit
Last active July 10, 2018 15:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save freddi-kit/828337b50e71b4a5936d21c0a50267c5 to your computer and use it in GitHub Desktop.
Save freddi-kit/828337b50e71b4a5936d21c0a50267c5 to your computer and use it in GitHub Desktop.
MargeSort implemented by Swift
//: Playground - noun: a place where people can play
import UIKit
func mergeSort<T: Comparable>(array: inout Array<T>, low: Int, high: Int){
guard low < high else {
return
}
let center:Int = (low + high) / 2
mergeSort(array: &array, low: low, high: center)
mergeSort(array: &array, low: center + 1, high: high)
var left = low
var right = center + 1
var tempArray: Array<T> = []
print("before :", array[low...high])
while(left <= center && right <= high) {
if array[left] > array[right] {
tempArray.append(array[right])
right += 1
} else {
tempArray.append(array[left])
left += 1
}
if left > center {
for i in right...high {
tempArray.append(array[i])
}
break
}
else if right > high {
for i in left...center {
tempArray.append(array[i])
}
break
}
}
for i in low...high {
array[i] = tempArray[i - low]
}
print("after :", array[low...high])
}
var array = [10,5,4,8,6,5]
mergeSort(array: &array, low: 0, high: array.count - 1)
print(array)
var arrayString = ["now", "can", "hoge", "fuga"]
mergeSort(array: &arrayString, low: 0, high: arrayString.count - 1)
print(arrayString)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment