Created
November 6, 2021 00:15
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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