How do I implement binary search in Swift?

Binary search is an efficient algorithm for finding a target value within a sorted array. It reduces the search space by half with each step, making it faster than linear search, especially for large lists.

Here is how you can implement binary search in Swift:

func binarySearch(array: [Int], target: Int) -> Int? { var left = 0 var right = array.count - 1 while left <= right { let mid = left + (right - left) / 2 if array[mid] == target { return mid } if array[mid] < target { left = mid + 1 } else { right = mid - 1 } } return nil // Target not found } // Example usage let numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9] if let index = binarySearch(array: numbers, target: 4) { print("Element found at index: \(index)") } else { print("Element not found.") }

binary search swift algorithm sorted array efficient search