Search code examples
arraysswifttypesbinary-search

Swift: Binary search for standard array?


I have a sorted array and want to do binary search on it.

So I'm asking if something is already available in Swift library like sort etc.? Or is there a type independend version available?

Of course I could write it by my own, but I like to avoid reinventing the wheel again.


Solution

  • Here's a generic way to use binary search:

    func binarySearch<T:Comparable>(_ inputArr:Array<T>, _ searchItem: T) -> Int? {
        var lowerIndex = 0
        var upperIndex = inputArr.count - 1
    
        while (true) {
            let currentIndex = (lowerIndex + upperIndex)/2
            if(inputArr[currentIndex] == searchItem) {
                return currentIndex
            } else if (lowerIndex > upperIndex) {
                return nil
            } else {
                if (inputArr[currentIndex] > searchItem) {
                    upperIndex = currentIndex - 1
                } else {
                    lowerIndex = currentIndex + 1
                }
            }
        }
    }
    
    var myArray = [1,2,3,4,5,6,7,9,10]
    if let searchIndex = binarySearch(myArray, 5) {
        print("Element found on index: \(searchIndex)")
    }