Swift Language Algorithms with Swift Insertion Sort


Insertion sort is one of the more basic algorithms in computer science. The insertion sort ranks elements by iterating through a collection and positions elements based on their value. The set is divided into sorted and unsorted halves and repeats until all elements are sorted. Insertion sort has complexity of O(n2). You can put it in an extension, like in an example below, or you can create a method for it.

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