给Array添加延展
extension Array where Element == Int {
/// 二分查找:判断有序的数组里面是否包含某一个数字
func binarySearch(x: Int) -> Bool {
var result = false
let min = self.startIndex
let max = self.endIndex - 1
if min > max {
return false
}
let mid = Int((min + max)/2)
let value = self[mid]
if x == value {
return true
}
if x < value {
let array = min < mid ? Array(self[min..<mid]) : Array<Int>()
result = array.binarySearch(x: x)
}
if x > value {
let array = max > mid ? Array(self[mid..<max]) : Array<Int>()
result = array.binarySearch(x: x)
}
return result
}
}