Created
May 24, 2017 06:15
-
-
Save chriswebb09/32175d2a4e7d971b54322da8fa74ed7a 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
| extension Array { | |
| mutating func swapItems(itemAtIndex firstIndex: Index, withItemAtIndex secondIndex: Index) { | |
| if firstIndex != secondIndex { | |
| swap(&self[firstIndex], &self[secondIndex]) | |
| } | |
| } | |
| } | |
| extension Sequence where Iterator.Element: Comparable { | |
| static func selectionSort(_ items: [Iterator.Element]) -> [Iterator.Element] { | |
| var results = items | |
| var length = results.count | |
| for i in 0..<length { | |
| var minIndex = i | |
| for j in i + 1..<length { | |
| if results[j] < results[minIndex] { | |
| minIndex = j | |
| } | |
| results.swapItems(itemAtIndex: i, withItemAtIndex: minIndex) | |
| } | |
| } | |
| return results | |
| } | |
| static func insertionSort(_ items: [Iterator.Element]) -> [Iterator.Element] { | |
| var results = items | |
| let length = results.count | |
| for i in 1..<length { | |
| for j in stride(from: i, to: 0, by: -1) { | |
| if results[j] < results[j - 1] { | |
| results.swapItems(itemAtIndex: j, withItemAtIndex: j - 1) | |
| } else { | |
| break | |
| } | |
| } | |
| } | |
| return results | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment