Two sections. One sorted. One unsorted. Select the smallest/largest value in the unsorted section and place it at the end of the sorted section. Continue until no values are left in the unsorted section.

func selectionSort(array: inout [Int]) -> [Int] {
    for i in 0 ..< array.count - 1 {
        var indexOfSmallestValue = i
        for j in i ..< array.count {
            indexOfSmallestValue = array[j] < array[indexOfSmallestValue] ? j : indexOfSmallestValue
        }
        array.swapAt(i, indexOfSmallestValue)
    }
    return array
}

Leave a Reply