Last active
June 29, 2016 06:37
-
-
Save mattgallagher/5caec92637aeccbd79b78cac150cc54d to your computer and use it in GitHub Desktop.
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
import Swift | |
let a = [5,2,7,2,8,8,10,0] | |
func selectionSort<S: Sequence where S.Iterator.Element: Comparable>( _ input: S) -> [S.Iterator.Element] { | |
return sequence(first: (remaining: Array(input.enumerated()), smallest: nil as S.Iterator.Element?)) { tuple in | |
tuple.remaining.min { left, right in | |
left.element < right.element | |
}.map { (pair: (offset: Int, element: S.Iterator.Element)) in | |
(tuple.remaining.filter { $0.offset != pair.offset }, pair.element) | |
} | |
}.flatMap { tuple in tuple.smallest } | |
} | |
let c = selectionSort(a) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This is a response to:
http://ericasadun.com/2016/06/28/make-it-swifter-challenge/
I wanted to operate over a Sequence and be non-recursive. If you relax those restrictions then something like this is much more compact:
In any case, these sorts of implementations should never be used in imperative/eager languages (functional/lazy languages may optimize some of the problems of these approaches away). These implementations are complexity O(n^3) due to creating a new array for each iteration of the sequence – a good selection sort should be O(n^2). If you want to use selection sort for some weird reason, look around for an in-place version that swaps the smallest element to the front rather than any silly approach like this.