NSArray具有- (NSUInteger)indexOfObject:(id)obj inSortedRange:(NSRange)r options:(NSBinarySearchingOptions)opts usingComparator:(NSComparator)cmp以确定新对象在排序数组中的插入位置。

在纯Swift中,最好的高性能方法是什么?

类似于以下内容:

var myArray = ["b", "e", "d", "a"]
myArray.sort { $0 < $1 }

// myArray is now [a, b, d, e]

myArray.append("c")
myArray.sort { $0 < $1 }

// myArray is now [a, b, c, d, e]


我不想附加新元素然后对数组进行排序,而是想出正确的位置并插入元素:

let index = [... how to calculate this index ??? ...]
myArray.insert("c", atIndex: index)

最佳答案

这是Swift中可能使用二进制搜索的实现(来自
http://rosettacode.org/wiki/Binary_search#Swift,稍作修改):

extension Array {
    func insertionIndexOf(_ elem: Element, isOrderedBefore: (Element, Element) -> Bool) -> Int {
        var lo = 0
        var hi = self.count - 1
        while lo <= hi {
            let mid = (lo + hi)/2
            if isOrderedBefore(self[mid], elem) {
                lo = mid + 1
            } else if isOrderedBefore(elem, self[mid]) {
                hi = mid - 1
            } else {
                return mid // found at position mid
            }
        }
        return lo // not found, would be inserted at position lo
    }
}


indexOfObject:inSortedRange:options:usingComparator:一样,假定
数组是根据比较器排序的。
如果元素已经存在于元素中,则它返回元素的(任意)索引。
数组,或在保留顺序时可在其中插入的索引。这个
对应于NSBinarySearchingInsertionIndex方法的NSArray

用法:

let newElement = "c"
let index = myArray.insertionIndexOf(newElement) { $0 < $1 } // Or: myArray.indexOf(c, <)
myArray.insert(newElement, at: index)

10-07 19:14
查看更多