perform a binary search in swift

Here's an implementation of binary search in Swift:

main.swift
func binarySearch<T: Comparable>(array: [T], key: T) -> Int? {
    var left = 0
    var right = array.count - 1
    
    while left <= right {
        let middle = (left + right) / 2
        if array[middle] == key {
            return middle
        } else if array[middle] < key {
            left = middle + 1
        } else {
            right = middle - 1
        }
    }
    
    return nil
}
399 chars
18 lines

To perform binary search, call this function passing it the array you want to search and the key you want to find. The function will return the index of the key in the array, or nil if the key is not found.

Here's an example of how to use it:

main.swift
let numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
if let index = binarySearch(array: numbers, key: 5) {
    print("Found 5 at index \(index)")
} else {
    print("5 not found")
}
175 chars
7 lines

This will output "Found 5 at index 4".

gistlibby LogSnag