Skip to content

Instantly share code, notes, and snippets.

@hossamghareeb
Created April 16, 2018 18:50
Show Gist options
  • Save hossamghareeb/49cdb01a03d5e43b3702873817fc1c91 to your computer and use it in GitHub Desktop.
Save hossamghareeb/49cdb01a03d5e43b3702873817fc1c91 to your computer and use it in GitHub Desktop.
Binary search Swift
/**
Returns index of item if found. Otherwise returns -1 * position where the item should be insertd to
*/
func binarySearch(arr: [Int], start: Int, end: Int, k: Int) -> Int {
var start = start
var end = end
var mid = 0
while start <= end {
mid = start + (end - start) / 2
if arr[mid] == k {
return mid
}
if arr[mid] < k {
// right side
start = mid + 1
} else {
end = mid - 1
}
}
return -1 * start
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment