Created
March 27, 2021 08:56
-
-
Save oconnelltoby/08cfb44b439e4c6f5b174c75f7fd4d8c to your computer and use it in GitHub Desktop.
Iterative binary search
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
extension RandomAccessCollection where Element: Comparable { | |
func binarySearch(target: Element) -> Index? { | |
guard !isEmpty else { | |
return nil | |
} | |
var start = startIndex | |
var end = endIndex | |
while start <= end { | |
let half = distance(from: start, to: end) / 2 | |
let middleIndex = index(start, offsetBy: half) | |
let middleValue = self[middleIndex] | |
if middleValue == target { | |
return middleIndex | |
} else if target < middleValue { | |
end = index(before: middleIndex) | |
} else { | |
start = index(after: middleIndex) | |
} | |
} | |
return nil | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment