Skip to content

Instantly share code, notes, and snippets.

@mattgallagher
Last active June 29, 2016 06:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mattgallagher/5caec92637aeccbd79b78cac150cc54d to your computer and use it in GitHub Desktop.
Save mattgallagher/5caec92637aeccbd79b78cac150cc54d to your computer and use it in GitHub Desktop.
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)
@mattgallagher
Copy link
Author

mattgallagher commented Jun 29, 2016

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:

func selectionSort<E: Comparable>(_ a: [E]) -> [E] {
   return a.enumerated().min { $0.element < $1.element }.map { m in
      [m.element] + selectionSort(a.enumerated().filter { $0.offset != m.offset }.map { $0.element })
   } ?? []
}

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment