Skip to content

Instantly share code, notes, and snippets.

@AdrianFerreyra
Created October 31, 2017 12:41
Show Gist options
  • Save AdrianFerreyra/98e93587b45d596b7cec57adb61392f5 to your computer and use it in GitHub Desktop.
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.
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