Skip to content

Instantly share code, notes, and snippets.

@oozoofrog
Last active July 9, 2016 17:55
Show Gist options
  • Save oozoofrog/a0c2bffea640564a5974fc8cc74dd35b to your computer and use it in GitHub Desktop.
Save oozoofrog/a0c2bffea640564a5974fc8cc74dd35b to your computer and use it in GitHub Desktop.
Array has moveForMin.
It is find min from &lt;from&gt; index <br/>**- from was bad choice. i thought -**
<br/>and move to &lt;moveTo&gt;
```objc
extension Array where Element: Comparable{
mutating func moveForMin(offset: Int = 0, moveTo to: Int) {
let subArray = self[offset..<self.count]
guard let minValue = subArray.min(isOrderedBefore: <) else {
return
}
guard let index = subArray.index(of: minValue) else {
return
}
self.remove(at: index)
self.insert(minValue, at: to)
}
}
```
Int has loop function. just loop helper
```objc
extension Int {
func loop(_ handle:(index: Int) -> Void) {
(0..<self).forEach(handle)
}
}
```
and.. selection sort
selection is simple but, like *the tip of an iceberg*
```objc
func selectionSort(_ array: [Int]) -> [Int] {
var sorted = array
guard 1 < array.count else {
return array
}
array.count.loop { from in
sorted.moveForMin(offset: from, moveTo: from)
}
return sorted
}
```
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment