Skip to content

Instantly share code, notes, and snippets.

@msepcot
Created November 6, 2021 00:15
Show Gist options
  • Save msepcot/81f4d2c73e44b155d9c8b2d0bc0e9f12 to your computer and use it in GitHub Desktop.
Save msepcot/81f4d2c73e44b155d9c8b2d0bc0e9f12 to your computer and use it in GitHub Desktop.
Binary Search extension on RandomAccessCollection that lets the caller do the compare on each element.
public extension RandomAccessCollection {
func binarySearch(comparing: (Element) -> ComparisonResult) -> Element? {
var lowerBound = startIndex
var upperBound = endIndex
while lowerBound < upperBound {
let size = distance(from: lowerBound, to: upperBound)
let midIndex = index(lowerBound, offsetBy: size / 2)
switch comparing(self[midIndex]) {
case .orderedSame:
return self[midIndex]
case .orderedAscending: // self[midIndex] is smaller than what we are looking for
lowerBound = index(midIndex, offsetBy: 1)
case .orderedDescending: // self[midIndex] is larger than what we are looking for
upperBound = midIndex
}
}
return nil
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment