Skip to content

Instantly share code, notes, and snippets.

@oconnelltoby
Created March 27, 2021 08:56
Show Gist options
  • Save oconnelltoby/08cfb44b439e4c6f5b174c75f7fd4d8c to your computer and use it in GitHub Desktop.
Save oconnelltoby/08cfb44b439e4c6f5b174c75f7fd4d8c to your computer and use it in GitHub Desktop.
Iterative binary search
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