LeetCode二分查找 swift 面试

 

func binarySearch(_ array: [Int], _ target: Int) -> Int? {
    var left = 0
    var right = array.count - 1
    
    while left <= right {
        let mid = (left + right) / 2
        
        if array[mid] == target {
            return mid
        } else if array[mid] < target {
            left = mid + 1
        } else {
            right = mid - 1
        }
    }
    
    return nil // 如果目标值不存在于数组中则返回nil
}
 
let numbers = [1, 3, 5, 7, 9, 11, 13]
if let index = binarySearch(numbers, 7) {
    print("目标值 \(index) 在数组中")
} else {
    print("目标值未找到")
}

 

posted @ 2024-02-26 21:05  黄增松  阅读(7)  评论(0编辑  收藏  举报