Skip to content

Instantly share code, notes, and snippets.

@coreyd303

coreyd303/mergeSort.swift

Last active Jun 1, 2020
Embed
What would you like to do?
SwiftyAlgos: Merge Sort
import UIKit
// Merge sort in Swift
// Split arrays
func mergeSort(array: [Int]) -> [Int] {
guard array.count > 1 else {
return array
}
let leftArray = Array(array[0..<array.count/2])
let rightArray = Array(array[array.count/2..<array.count])
return merge(leftArray: mergeSort(array: leftArray), rightArray: mergeSort(array: rightArray))
}
// mergeArrays
func merge(leftArray: [Int], rightArray: [Int]) -> [Int] {
var mergeList = [Int]()
var left = leftArray
var right = rightArray
while left.count > 0 && right.count > 0 {
if left.first! < right.first! {
mergeList.append(left.removeFirst())
} else {
mergeList.append(right.removeFirst())
}
}
return mergeList + left + right
}
var numbers = [Int]()
for _ in 0..<50 {
numbers.append(Int(arc4random_uniform(UInt32(1000))))
}
let sorted = mergeSort(array: numbers)
print(numbers)
print()
print(sorted)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment