2018-08-08 swift_Binary Search
2018-08-08 本文已影响0人
朝九晚九
Binary Search是二分查找,将目标分成两部分来进行查找,相比顺序查找效率要高一些,例如在书店中,20本书里有一本书没有被消磁,按照顺序可能会查到最后第20本才会找到,但是如果分成两部分一次就可以排除10本书,效率提高很多。
func binarySearch<T: Comparable>(_ a: [T], key: T, range: Range<Int>) -> Int? {
if range.lowerBound >= range.upperBound {
// If we get here, then the search key is not present in the array.
return nil
} else {
// Calculate where to split the array.
let midIndex = range.lowerBound + (range.upperBound - range.lowerBound) / 2
// Is the search key in the left half?
if a[midIndex] > key {
return binarySearch(a, key: key, range: range.lowerBound ..< midIndex)
// Is the search key in the right half?
} else if a[midIndex] < key {
return binarySearch(a, key: key, range: midIndex + 1 ..< range.upperBound)
// If we get here, then we've found the search key!
} else {
return midIndex
}
}
}
let numbers = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67]
binarySearch(numbers, key: 43, range: 0 ..< numbers.count)
在分四次之后找到了43
需要注意的是二分查找的元素是按照顺序排列的