Algorithm
See: Swift: Binary Search Algorithm (iOS Interview Prep) 2022 - YouTube
-
Given:
-
- array of values
-
- a target value
-
-
Find: the index for the target value
-
Precondition: The values must be presorted
Pseudo code
- Find the midpoint value
left
= start indexright
= end index- Loop:
middleIndex
= midpoint betweenleft
andright
- lookup
middleValue
atmiddleIndex
- If:
middleValue
value >target
:- then: decrement
right
- then: decrement
- else if:
middleValue
<target
- then: increment
left
- then: increment
- else if
middleValue
==target
- then: return the index