본문 바로가기

프로그래밍/iOS,macOS

[swift] sorted array 에 값 추가

WWDC 2018 Session 406 : Divide-and-Conquer Binary Search

stackoverflow : sorting - How do I insert an element at the correct position into a sorted array in Swift?

 

func sortedInsertionValue(_ value: String) {
    var slice: Array<String>.SubSequence = mySortedArray[...]
    while !slice.isEmpty {
       let middle = slice.index(slice.startIndex, offsetBy: slice.count / 2 )
       if value < slice[middle] {
           slice = slice[..<middle]
       } else {
           slice = slice[slice.index(after: middle)...]
       }
    }
    mySortedArray.insert(value, at: slice.startIndex)
}