Skip to content

Instantly share code, notes, and snippets.

@chriswebb09
Created May 24, 2017 06:15
Show Gist options
  • Select an option

  • Save chriswebb09/32175d2a4e7d971b54322da8fa74ed7a to your computer and use it in GitHub Desktop.

Select an option

Save chriswebb09/32175d2a4e7d971b54322da8fa74ed7a to your computer and use it in GitHub Desktop.
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