Created
April 27, 2021 14:50
-
-
Save thatswiftguy/8d4ffaa06786581ed68a957fa7627c8e to your computer and use it in GitHub Desktop.
Merge sort algorithm
This file contains hidden or 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
var array2 = [4,2,2,5,7,2,1,9,3] | |
func merge(left:[Int],right:[Int]) -> [Int] { | |
var mergedList = [Int]() | |
var l = left | |
var r = right | |
while l.count > 0 && r.count > 0 { | |
if l.first! < r.first! { | |
mergedList.append(l.removeFirst()) | |
} else { | |
mergedList.append(r.removeFirst()) | |
} | |
} | |
return mergedList + l + r | |
} | |
func mergeSort(list:[Int]) -> [Int] { | |
guard list.count > 1 else { | |
return list | |
} | |
let leftList = Array(list[0..<list.count/2]) | |
let rightList = Array(list[list.count/2..<list.count]) | |
return merge(left: mergeSort(list:leftList), right: mergeSort(list:rightList)) | |
} | |
print(mergeSort(list: array2)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment