///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)
网友评论