二分查找主要是找出中间值,如果目标值在中间值左边,就将搜索区域移动到左边,如果在右边移动到右边
let list = [1,4,6,9,10,33,45,66,77]
func binarySearch(_ array:[Int], _ targat:Int) -> (Int,Bool){
var left = 0, right = array.count-1, middel = 0
while left <= right {
middel = left + (right - left)/2
if array[middel] == targat {
return (middel,true)
}
if array[middel] < targat {
left = middel+1
}else{
right = middel-1
}
}
return (-1,false)
}
print(binarySearch(list, 78))
时间复杂度 O(log2n)
网友评论