Created
October 31, 2017 12:41
-
-
Save AdrianFerreyra/98e93587b45d596b7cec57adb61392f5 to your computer and use it in GitHub Desktop.
A brief recursive implementation of InsertionSort on generic Comparable element's arrays in Swift 4.
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 | |
//InsertionSort | |
///Inserts a value into a sorted array | |
func insert<T: Comparable>(value: T,into array: [T]) -> [T] { | |
guard let last = array.last else { | |
return [value] | |
} | |
if value < last { | |
return insert(value: value, into: Array(array.dropLast())) + [last] | |
} else { | |
return array + [value] | |
} | |
} | |
//Sort an array using InsertionSort recursively. | |
func insertionSort<T: Comparable>(_ array: [T]) -> [T] { | |
guard let last = array.last else { | |
return [] | |
} | |
return insert(value: last,into: insertionSort(Array(array.dropLast()))) | |
} | |
let unsortedArray = [2,1,3,7,5,6,4,8,9] | |
let sorterArray = insertionSort(unsortedArray) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment