Created
October 31, 2017 03:25
-
-
Save AdrianFerreyra/f545a72cf5144b952a24224a11c38ef6 to your computer and use it in GitHub Desktop.
In-Situ implementation of MergeSort
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 Foundation | |
//Merge Sort | |
func merge<T: Comparable>(_ lhs: [T],_ rhs: [T]) -> [T] { | |
switch (lhs,rhs) { | |
case (let lhs, let rhs) where lhs.count == 0: | |
return rhs | |
case (let lhs, let rhs) where rhs.count == 0: | |
return lhs | |
case (let lhs, let rhs) where lhs.first! < rhs.first!: | |
return [lhs.first!] + merge(Array(lhs.dropFirst()), rhs) | |
default: | |
return [rhs.first!] + merge(lhs, Array(rhs.dropFirst())) | |
} | |
} | |
func mergesort<T: Comparable>(_ array: [T]) -> [T] { | |
guard array.count >= 2 else { | |
return array | |
} | |
return merge( | |
mergesort( | |
Array(array.dropLast(array.count - Int(array.count/2))) | |
), | |
mergesort( | |
Array(array.dropFirst(Int(array.count/2))) | |
)) | |
} | |
let array = [3,4,6,1,7,2] | |
let a = mergesort(array) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment