Bubble Sort in Swift

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


bubble-sort in Swift

func bubbleSort(array: inout [Int]) {
    var n = array.count
    while (n > 0) {
        var lastModifiedIndex = 0
        for currentIndex in 1..<n {
            // if the item at the previous index is greater than the item at the `currentIndex`, swap them
            if array[currentIndex - 1] > array[currentIndex] {
                // swap
                let temp = array[currentIndex - 1]
                array[currentIndex - 1] = array[currentIndex]
                array[currentIndex] = temp
                // save the index that was modified
                lastModifiedIndex = currentIndex
            }
        }
        // save the last modified index so we know not to iterate past it since all proceeding values are sorted
        n = lastModifiedIndex
    }
}

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

Discussion