Created
April 16, 2018 18:50
-
-
Save hossamghareeb/49cdb01a03d5e43b3702873817fc1c91 to your computer and use it in GitHub Desktop.
Binary search Swift
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
/** | |
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