Skip to content

Instantly share code, notes, and snippets.

@davidinga
Created August 24, 2019 02:38
Show Gist options
  • Select an option

  • Save davidinga/dc3485fdd81fce880c412a1b553e3ec1 to your computer and use it in GitHub Desktop.

Select an option

Save davidinga/dc3485fdd81fce880c412a1b553e3ec1 to your computer and use it in GitHub Desktop.
Iterative Binary Search algorithm implemented in Swift. Returns an optional index given a target element and an array of the same type. Time complexity of O(logn) and space complexity of O(1).
func binarySearch<Element>(for target: Element, in array: [Element]) -> Int? where Element: Comparable {
var L = 0
var R = array.count - 1
var mid = 0
while L <= R {
//// Index of middle element.
mid = L + (R - L) / 2
//// Middle element is target; return it.
if array[mid] == target {
return mid
}
//// Middle element greater than target; ignore right.
if array[mid] > target {
R = mid - 1
//// Middle element is less than target; ignore left.
} else {
L = mid + 1
}
}
return nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment