Created
August 24, 2019 02:38
-
-
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).
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<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