Created
November 6, 2017 19:41
-
-
Save arashkashi/e620b02d88131330036b177e1e5e7d73 to your computer and use it in GitHub Desktop.
binary search
This file contains hidden or 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(item: Int, in A: [Int]) -> Int? { | |
var beg = 0 | |
var end = A.count - 1 | |
var result: Int? | |
while end - beg >= 1 { | |
var mid = (beg + end) / 2 | |
if item < A[mid] { | |
end = mid - 1 | |
} else { | |
beg = mid + 1 | |
} | |
if A[mid] == item { result = mid; break } | |
if end == beg && A[end] == item { result = mid; break } | |
} | |
return result | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment