let origin = [1, 3, 43, 54, 99, 8, 7, 12, 6, 5]
func mergeSort(_ array: [Int]) {
guard array.count > 1 else {
print("wrong input")
return
}
func merge_sort(_ array: [Int]) -> [Int] {
guard array.count > 1 else {
return array
}
let mid = array.count / 2 - 1
let leftArray = Array(array[0...mid])
let rightArray = Array(array[(mid+1)...array.count-1])
return merge(merge_sort(leftArray), merge_sort(rightArray))
}
func merge(_ left: [Int], _ right: [Int]) -> [Int] {
var merged = [Int]()
var leftIndex = 0
var rightIndex = 0
while leftIndex < left.count && rightIndex < right.count {
if left[leftIndex] > right[rightIndex] {
merged.append(left[leftIndex])
leftIndex += 1
}else {
merged.append(right[rightIndex])
rightIndex += 1
}
}
if leftIndex < left.count {
for i in leftIndex..<left.count {
merged.append(left[i])
}
}
if rightIndex < right.count {
for i in rightIndex..<right.count {
merged.append(right[i])
}
}
return merged
}
let result = merge_sort(array)
print("merge sort result: \(result))")
}
mergeSort(origin)