Last active
April 18, 2020 11:02
-
-
Save monsoir/06d561b04ac8699cda3bb994b8b3d526 to your computer and use it in GitHub Desktop.
Algorithms in Swift
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 Array where Element: Comparable { | |
func binarySearch(_ target: Element) -> Int? { | |
var lower = 0 | |
var upper = count | |
while lower < upper { | |
let mid = lower + (upper - lower) / 2 | |
if self[mid] == target { | |
return mid | |
} else if self[mid] < target { | |
lower = mid + 1 | |
} else { | |
upper = mid | |
} | |
} | |
return nil | |
} | |
} | |
let numbers = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67] | |
print(numbers.binarySearch(100) ?? -1) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment