Last active
July 9, 2016 17:55
-
-
Save oozoofrog/a0c2bffea640564a5974fc8cc74dd35b 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
Array has moveForMin. | |
It is find min from <from> index <br/>**- from was bad choice. i thought -** | |
<br/>and move to <moveTo> | |
```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