Algorithm/Data structure

Swift - selection sort

Teol 2023. 11. 4. 00:38

- 선택 정렬


selection sort 는 배열에서 가장 작은 값을 찾아서 맨 앞의 값과 교환하는 과정을 반복하는 정렬 알고리즘이다.
시간 복잡도는 O(n^2) 이다.

func selectionSort(_ array: [Int]) -> [Int] {
    var sortedArray = array
    let n = sortedArray.count
    for i in 0..<n {
        var minIndex = i
        for j in i+1..<n {
            if sortedArray[minIndex] > sortedArray[j] {
                minIndex = j
            }
//            print(i, "->", j, "=>", minIndex, terminator: " ")
        }

        if i != minIndex {
            sortedArray.swapAt(i, minIndex)
        }
//        print(sortedArray)
    }

    return sortedArray
}

print( selectionSort([5,3,6,2,1]) )

 

 

 

 

'Algorithm > Data structure' 카테고리의 다른 글

Swift - Queue구현  (0) 2023.12.04
Swift - quick sort  (0) 2023.11.04
Swift - bubble sort  (0) 2023.11.03