Insertion Sort in Swift

Below is an example of the Insertion Sort algorithm in Swift. See the Insertion Sort page for more information and implementations.


insertion-sort in Swift

func insertionSort(array: inout [Int]) {
    // start at the first index and iterate through to the end
    for i in 1..<array.count {
        var currentIndex = i
        /*
         * Check:
         *      1. that currentIndex is at least 1
         *      2. that the item directly before the currentIndex is greater than the item at currentIndex
         *
         * If both conditions are met, swap the indexes
         */
        while currentIndex > 0 && array[currentIndex - 1] > array[currentIndex] {
            let temp = array[currentIndex]
            array[currentIndex] = array[currentIndex - 1]
            array[currentIndex - 1] = temp
            currentIndex -= 1
        }
    }
}

var array = [12, 11, 15, 10, 9, 1, 2, 3, 13, 14, 4, 5, 6, 7, 8]
insertionSort(array: &array)
print(array)

Discussion