|
| 1 | +/** |
| 2 | + Binary Search |
| 3 | + |
| 4 | + |
| 5 | + Recursively splits the array in half until the value is found. |
| 6 | + |
| 7 | + If there is more than one occurrence of the search key in the array, then |
| 8 | + there is no guarantee which one it finds. |
| 9 | + |
| 10 | + Note: The array must be sorted! |
| 11 | + You can find the documentation on https://www.raywenderlich.com/139821/swift-algorithm-club-swift-binary-search-tree-data-structure] |
| 12 | + **/ |
| 13 | + |
| 14 | +import Foundation |
| 15 | + |
| 16 | +// The recursive version of binary search. |
| 17 | + |
| 18 | +public func binarySearch<T: Comparable>(_ a: [T], key: T, range: Range<Int>) -> Int? { |
| 19 | + if range.lowerBound >= range.upperBound { |
| 20 | + return nil |
| 21 | + } else { |
| 22 | + let midIndex = range.lowerBound + (range.upperBound - range.lowerBound) / 2 |
| 23 | + if a[midIndex] > key { |
| 24 | + return binarySearch(a, key: key, range: range.lowerBound ..< midIndex) |
| 25 | + } else if a[midIndex] < key { |
| 26 | + return binarySearch(a, key: key, range: midIndex + 1 ..< range.upperBound) |
| 27 | + } else { |
| 28 | + return midIndex |
| 29 | + } |
| 30 | + } |
| 31 | +} |
| 32 | + |
| 33 | +/** |
| 34 | + The iterative version of binary search. |
| 35 | + |
| 36 | + Notice how similar these functions are. The difference is that this one |
| 37 | + uses a while loop, while the other calls itself recursively. |
| 38 | + **/ |
| 39 | + |
| 40 | +public func binarySearch<T: Comparable>(_ a: [T], key: T) -> Int? { |
| 41 | + var lowerBound = 0 |
| 42 | + var upperBound = a.count |
| 43 | + while lowerBound < upperBound { |
| 44 | + let midIndex = lowerBound + (upperBound - lowerBound) / 2 |
| 45 | + if a[midIndex] == key { |
| 46 | + return midIndex |
| 47 | + } else if a[midIndex] < key { |
| 48 | + lowerBound = midIndex + 1 |
| 49 | + } else { |
| 50 | + upperBound = midIndex |
| 51 | + } |
| 52 | + } |
| 53 | + return nil |
| 54 | +} |
0 commit comments