Skip to content

Instantly share code, notes, and snippets.

@koher
Created May 1, 2021 14:24
Show Gist options
  • Save koher/45a4aa08d86addcf40e371a106ca2b1f to your computer and use it in GitHub Desktop.
Save koher/45a4aa08d86addcf40e371a106ca2b1f to your computer and use it in GitHub Desktop.
func binarySearch<Values>(_ value: Values.Element, in values: Values) -> Int? where Values: Collection, Values.Element: Comparable, Values.Index == Int {
var values: Values.SubSequence = values[...]
while !values.isEmpty {
let midIndex = values.startIndex + (values.endIndex - values.startIndex) / 2
let midValue = values[midIndex]
if value < midValue {
values = values[..<midIndex]
} else if value > midValue {
values = values[(midIndex + 1)...]
} else {
return midIndex
}
}
return nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment