Swift 实现二分法查找

let A = [1, 2, 3, 4, 5]
let key = 4

func binarySearch(A: [Int], key: Int) -> Int {
    var startIndex = 0
    var endIndex = A.count - 1
    var midIndex = (startIndex + endIndex) / 2
    var midValue = A[midIndex]
    let maxTimes = Int(log2(Double(A.count)).rounded(.up))
    var currentTimes = 1
    while midValue != key {
        if key < midValue {
            endIndex = midIndex
            midIndex = (startIndex + endIndex) / 2
            midValue = A[midIndex]
        }
        else if key > midValue {
            startIndex = midIndex
            midIndex = Int(((Double(startIndex) + Double(endIndex)) / 2.0).rounded(.up))
            midValue = A[midIndex]
        }
        
        currentTimes += 1
        if currentTimes == maxTimes {
            break
        }
    }
    if midValue == key {
        return midIndex
    }
    return -1
}

let result = binarySearch(A: A, key: key)
print(result)

你可能感兴趣的:(Swift 实现二分法查找)