Created
May 1, 2021 14:24
-
-
Save koher/45a4aa08d86addcf40e371a106ca2b1f to your computer and use it in GitHub Desktop.
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
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