Skip to content

wltrup/RandomAccessCollectionBinarySearch

Repository files navigation

RandomAccessCollectionBinarySearch

Xcode Swift GitHub tag (latest SemVer) GitHub

What

RandomAccessCollectionBinarySearch is a Swift Package Manager package for iOS/tvOS (10.0 and above), watchOS (4.0 and above), and macOS (10.14 and above), under Swift 5.0 and above, implementing an extension to RandomAccessCollection to add support for performing binary searches on sorted collections.

In particular, in addition to the "normal" binary search, the package provides a version that also returns the indices of the values "bracketing" the value being searched for, with sensible results in all possible situations.

public extension RandomAccessCollection where Element: Comparable {

    // Returns the index of the target element, if it exists in the
    // input collection, or `nil`, if it does not. It is assumed that
    // the collection is sorted.

    static func binarySearch(in input: Self, for targetElement: Element) -> Index?

    func binarySearch(for targetElement: Element) -> Index?

    // Returns a tuple containing the indices of the two collection elements
    // that narrowly bracket the target element in the input collection
    // (assumed sorted), as well as the index of the target element itself.

    static func binarySearchLoHi(in input: Self, for targetElement: Element)
        -> (low: Index?, target: Index?, high: Index?)

    func binarySearchLoHi(for targetElement: Element)
        -> (low: Index?, target: Index?, high: Index?)

}

Installation

RandomAccessCollectionBinarySearch is provided only as a Swift Package Manager package, because I'm moving away from CocoaPods and Carthage, and can be easily installed directly from Xcode.

License

RandomAccessCollectionBinarySearch is available under the MIT license. See the LICENSE file for more info.

About

No description, website, or topics provided.

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages