Last active
June 1, 2020 21:37
-
-
Save coreyd303/04ad16cf2eb8b4c4d9a4abc27c5441ee to your computer and use it in GitHub Desktop.
SwiftyAlgos: Merge Sort
This file contains 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
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