Insertion Sort
suggest changeInsertion sort is one of the more basic algorithms in computer science. It walks a collection and places each element according to its value. The collection is divided into sorted and unsorted parts, and the walk repeats until every element is sorted. A typical insertion sort is O(n²). The method below uses remove and insert inside the inner loop, so its cost is higher than a swap-based insertion sort. It can live in an extension, as in the example below, or as a free function.
extension Array where Element: Comparable {
func insertionSort() -> 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 {
let key = output[primaryindex]
var secondaryindex = primaryindex
while secondaryindex > -1 {
if key < output[secondaryindex] {
//move to correct position
output.remove(at: secondaryindex + 1)
output.insert(key, at: secondaryindex)
}
secondaryindex -= 1
}
}
return output
}
}
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents