Selection sort
suggest changeSelection sort is simple. It takes the first unsorted index as the minimum, walks the rest of the array, and replaces that minimum with any smaller value it finds. It then swaps that value into the unsorted index and repeats. It is O(n²). On nearly sorted data it is often slower than insertion sort.
extension Array where Element: Comparable {
func selectionSort() -> Array<Element> {
//check for trivial case
guard self.count > 1 else {
return self
}
//mutated copy
var output: Array<Element> = self
for primaryindex in 0..<output.count {
var minimum = primaryindex
var secondaryindex = primaryindex + 1
while secondaryindex < output.count {
//store lowest value as minimum
if output[minimum] > output[secondaryindex] {
minimum = secondaryindex
}
secondaryindex += 1
}
//swap minimum value with array iteration
if primaryindex != minimum {
output.swapAt(primaryindex, minimum)
}
}
return output
}
}
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents