Arrays 在数组中查找值的周围元素

Arrays 在数组中查找值的周围元素,arrays,swift,for-loop,indexing,Arrays,Swift,For Loop,Indexing,我有一个CGfloat数组。我还有一个任意值a,可以是任何CGFloat。我的问题是,如何有效地找到a介于哪两个指数之间。作为旁注,a永远不会小于或大于数组的最小值或最大值,因此无需担心这一点 举个简单的例子,我可能有: let array: [CGFloat] = [4, 7, 10, 22, 23, 25, 67] // a can be any random number, this initialization is for the example let a = 14 // som

我有一个CGfloat数组。我还有一个任意值a,可以是任何CGFloat。我的问题是,如何有效地找到a介于哪两个指数之间。作为旁注,a永远不会小于或大于数组的最小值或最大值,因此无需担心这一点

举个简单的例子,我可能有:

let array: [CGFloat] = [4, 7, 10, 22, 23, 25, 67]

// a can be any random number, this initialization is for the example
let a = 14

// some algorithm that calculates indexes
// code returns index 2 and 3 (or it returns items 10, 22)
我开发了一种涉及for循环的方法,但是,列表越大,代码的效率就越低。有没有更智能、更高效的代码


谢谢您的帮助:)

如果您的数组总是排序的,请使用:

let array: [CGFloat] = [4, 7, 10, 22, 23, 25, 67]
let a: CGFloat = 14
if let maxIndex = array.firstIndex(where: { $0 > a }), maxIndex > 0 {
    print("a between \(maxIndex - 1) and \(maxIndex) indexes")
}

如果您的数组始终排序,请使用:

let array: [CGFloat] = [4, 7, 10, 22, 23, 25, 67]
let a: CGFloat = 14
if let maxIndex = array.firstIndex(where: { $0 > a }), maxIndex > 0 {
    print("a between \(maxIndex - 1) and \(maxIndex) indexes")
}

您正在寻找的是所谓的中间二进制搜索。这种方法有很多例子。请注意,如果传递的值低于第一个值,它将返回起始索引,高于最后一个值的值将返回最后一个索引

extension Collection where Element: Comparable, Index == Int {
    func binarySearch(_ element: Element) -> Index {
        var low = 0
        var high = count - 1
        while low < high {
            let mid = low + ((high - low + 1) / 2)
            let current = self[mid]
            if current == element {
                return mid
            } else if current < element {
                low = mid
            } else {
                high = mid - 1
            }
        }
        return low
    }
}

您正在寻找的是所谓的中间二进制搜索。这种方法有很多例子。请注意,如果传递的值低于第一个值,它将返回起始索引,高于最后一个值的值将返回最后一个索引

extension Collection where Element: Comparable, Index == Int {
    func binarySearch(_ element: Element) -> Index {
        var low = 0
        var high = count - 1
        while low < high {
            let mid = low + ((high - low + 1) / 2)
            let current = self[mid]
            if current == element {
                return mid
            } else if current < element {
                low = mid
            } else {
                high = mid - 1
            }
        }
        return low
    }
}

输入数组是否已排序?一种可能的解决方案,
firstIndex(其中:)
,您可以找到第一个索引,其中的值大于您的值(这样就得到了上限)。然后,下一个索引,即该索引减去1。给定
a==10
,应该返回什么?请包括您自己尝试解决此问题的努力。相关:输入数组是否排序?一个可能的解决方案,
firstIndex(其中:)
,您会发现第一个索引的值大于您的值(通过这种方式得到上限)。那么,较低的索引是该索引减去1。给定
a==10
,应该返回什么?请包括您自己试图解决此问题的努力。相关: