arrays - Swift:二进制搜索标准数组?

标签 arrays swift types binary-search

我有一个排序数组,想对其进行二分查找。

所以我想问一下 Swift 库中是否已经提供了一些东西,比如 sort 等?或者是否有可用的类型独立版本?

我当然可以自己写,但我想避免重新造轮子。

最佳答案

这是我最喜欢的二分搜索实现。它不仅对查找元素很有用,而且对查找插入索引也很有用。通过提供相应的谓词(例如 { $0 < x } vs { $0 > x } vs { $0 <= x } vs { $0 >= x })来控制关于假定排序顺序(升序或降序)和相对于相等元素的行为的详细信息。注释明确说明了它的具体作用。

extension RandomAccessCollection {
    /// Finds such index N that predicate is true for all elements up to
    /// but not including the index N, and is false for all elements
    /// starting with index N.
    /// Behavior is undefined if there is no such N.
    func binarySearch(predicate: (Element) -> Bool) -> Index {
        var low = startIndex
        var high = endIndex
        while low != high {
            let mid = index(low, offsetBy: distance(from: low, to: high)/2)
            if predicate(self[mid]) {
                low = index(after: mid)
            } else {
                high = mid
            }
        }
        return low
    }
}

示例用法:

(0 ..< 778).binarySearch { $0 < 145 } // 145

关于arrays - Swift:二进制搜索标准数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31904396/

相关文章:

javascript - 尝试从数组中的子对象创建数组

ios - Moya/Alamofire 请求变量问题

声明期间的 Swift getter 语法

python - 我如何知道要使用什么类型的浮子?

java - 使用 Hibernate 映射 boolean[] PostgreSql 列

Java Queue 的 isFull 方法实现不带 nitems 字段

java - 创建一个数组,其中每个位置代表 enum 的一个元素

javascript - 借助扩展运算符修改对象的属性会导致原始对象被修改吗?

swift - 在 watchOS 5.2 崩溃时找不到适合组合的图像

php - 在 PHP SOAP 中传递用户定义的类型