美文网首页
Binary Search. Θ(lgn)

Binary Search. Θ(lgn)

作者: R0b1n_L33 | 来源:发表于2017-09-21 12:15 被阅读19次
    ///Binary Search Recursively. Θ(lgn)
    func binarySearch<T: Comparable>(target:T, sortedArray: [T]) -> Int? {
        guard sortedArray.count > 0 else { return nil }
        return _binarySearch(target: target, sortedArray: sortedArray, low: 0, high: sortedArray.count-1)
    }
    func _binarySearch<T: Comparable>(target:T, sortedArray: [T], low:Int, high:Int) -> Int? {
        guard low != high else { return target==sortedArray[low] ? low : nil }
        let mid = (high+low)/2
        if sortedArray[mid] > target {
            return _binarySearch(target: target, sortedArray: sortedArray, low: low, high: mid)
        } else if sortedArray[mid] < target {
            return _binarySearch(target: target, sortedArray: sortedArray, low: mid+1, high: high)
        }
        return mid
    }
    
    ///Binary Search Circularly. Θ(lgn)
    func binarySearch<T: Comparable>(target:T, sortedArray: [T]) -> Int? {
        guard sortedArray.count > 0 else { return nil }
        var mid = 0, low = 0, high = sortedArray.count-1
        while low != high {
            mid = (high+low)/2
            if sortedArray[mid] == target { return mid }
            if sortedArray[mid] > target  { high = mid }
            else { low = mid+1 }
        }
        return target==sortedArray[low] ? low : nil
    }
    
    let r = try Int.random(above: 0, under: 99)
    let s = Array(0...99)
    binarySearch(target: r, sortedArray: s)
    

    相关文章

      网友评论

          本文标题:Binary Search. Θ(lgn)

          本文链接:https://www.haomeiwen.com/subject/bmlzsxtx.html