⚡ TL;DR
Binary search a sorted array in Swift with working code. Iterative approach with O(log n) time, plus complexity analysis and interview tips.
Binary Search (#704 — Easy): Given an array of integers nums sorted in ascending order and an integer target, return the index of target in nums, or -1 if it is not present.
Problem Statement
Given an array of integers nums sorted in ascending order and an integer target, return the index of target in nums, or -1 if it is not present.
Example:
Input: nums = [-1,0,3,5,9,12], target = 9
Output: 4
Explanation: 9 exists at index 4.Approach: Iterative Two Pointers
Time: O(log n) | Space: O(1)
Keep lo and hi pointers on the search window. Compare the middle element with the target, discard the half that cannot contain it, and stop when the window closes — or the target is found.
func binarySearch(_ nums: [Int], _ target: Int) -> Int {
var lo = 0
var hi = nums.count - 1
while lo <= hi {
let mid = (lo + hi) / 2
if nums[mid] == target {
return mid
}
if nums[mid] < target {
lo = mid + 1
} else {
hi = mid - 1
}
}
return -1
}
let nums = [-1, 0, 3, 5, 9, 12]
print("Index of 9:", binarySearch(nums, 9))
print("Index of 2:", binarySearch(nums, 2))Approach: Recursive Divide & Conquer
Time: O(log n) | Space: O(log n)
The same halving expressed as recursion: search the left or right half until the window is empty. Same comparisons, but the call stack stores log n frames.
func binarySearchRecursive(_ nums: [Int], _ target: Int, _ lo: Int, _ hi: Int) -> Int {
if lo > hi {
return -1
}
let mid = (lo + hi) / 2
if nums[mid] == target {
return mid
}
if nums[mid] < target {
return binarySearchRecursive(nums, target, mid + 1, hi)
}
return binarySearchRecursive(nums, target, lo, mid - 1)
}
let nums = [-1, 0, 3, 5, 9, 12]
print("Index of 9:", binarySearchRecursive(nums, 9, 0, nums.count - 1))
print("Index of 2:", binarySearchRecursive(nums, 2, 0, nums.count - 1))Key Takeaways
- mid = (lo + hi) // 2 — integer division avoids float indices in every language
- The loop condition lo <= hi (not <) is the classic off-by-one trap
- Halving the window each step is what turns 1,000,000 elements into ~20 comparisons
FAQ
What is the best approach to solve Binary Search in Swift?
The recommended approach is Iterative Two Pointers, which runs in O(log n) time with O(1) space. The full Swift implementation is shown above.
What is the time complexity of Binary Search in Swift?
Using Iterative Two Pointers, the time complexity is O(log n) and the space complexity is O(1); Recursive Divide & Conquer runs in O(log n) time with O(log n) space.
Happy coding!

Written by Mihir Pipermitwala
Senior Full Stack Consultant & Mobile Engineering Specialist building user-focused applications in healthcare with Flutter, Dart and React Native. I write about what I actually build and test — every tutorial here comes from real project work.
More about Mihir →