Skip to content

Instantly share code, notes, and snippets.

@arashkashi
Created November 6, 2017 19:41
Show Gist options
  • Save arashkashi/e620b02d88131330036b177e1e5e7d73 to your computer and use it in GitHub Desktop.
Save arashkashi/e620b02d88131330036b177e1e5e7d73 to your computer and use it in GitHub Desktop.
binary search
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