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.")
}
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?