我要如何插入在正确的位置处的元素到斯威夫特一个排序的数组? [英] How do I insert an element at the correct position into a sorted array in Swift?

查看:124
本文介绍了我要如何插入在正确的位置处的元素到斯威夫特一个排序的数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

的NSArray - (NSUInteger)indexOfObject:(ID)OBJ inSortedRange:(NSRange)R选项:(NSBinarySearchingOptions)选择采用usingComparator:(NSComparator )CMP 来确定排序后的数组的新对象的插入位置。

什么是纯粹的斯威夫特做到这一点最好的和高性能的方式?

线沿线的东西:

  myarray的无功= [B,E,D,A]
myArray.sort {$ 0℃; $ 1}// myArray的现在是[A,B,D,E]myArray.append(C)
myArray.sort {$ 0℃; $ 1}// myArray的现在是[A,B,C,D,E]

而不是追加新的元素,然后进行排序数组的,我想弄清楚正确的位置并插入元素:

 让指数= [...如何计算这个指标? ...]
myArray.insert(C,atIndex:指数)


解决方案

下面是斯威夫特的一个可能实现使用二进制搜索(从
<一href=\"http://rosetta$c$c.org/wiki/Binary_search#Swift\">http://rosetta$c$c.org/wiki/Binary_search#Swift稍作修改):

 扩展阵列{
    FUNC insertionIndexOf(ELEM:T,isOrderedBefore:(T,T) - GT;布尔) - GT; INT {
        VAR LO = 0
        VAR HI = self.count - 1
        而LO&LT; = {喜
            让中期=(LO + HI)/ 2
            如果isOrderedBefore(个体经营[MID],ELEM){
                LO =中旬+ 1
            }否则如果isOrderedBefore(ELEM,自[MID]){
                HI =中旬 - 1
            }其他{
                返回中旬//发现在中间位置
            }
        }
        返回LO //没有找到,将在罗的位置被插入
    }
}

indexOfObject:inSortedRange:选项:usingComparator:假设
阵列相对于所述比较器进行排序。
它返回任一(任何)的元素的索引,如果该元件已经$在p $ psent
阵列,或者它可以在preserving的顺序被插入的索引。这个
对应于 NSBinarySearchingInsertionIndex 的NSArray 方法。

用法:

 让我们为newElement =C
让指数=​​ myArray.insertionIndexOf(为newElement){$ 0℃; $ 1} //或者:myArray.indexOf(C,≤)
myArray.insert(为newElement,atIndex:指数)

NSArray has - (NSUInteger)indexOfObject:(id)obj inSortedRange:(NSRange)r options:(NSBinarySearchingOptions)opts usingComparator:(NSComparator)cmp to determine the insert position of a new object in a sorted array.

What is the best and high-performance way to do this in pure Swift?

Something along the lines of:

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]

Instead of appending the new element and then sorting the array, I would like to figure out the correct position and insert the element:

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

解决方案

Here is a possible implementation in Swift using binary search (from http://rosettacode.org/wiki/Binary_search#Swift with slight modifications):

extension Array {
    func insertionIndexOf(elem: T, isOrderedBefore: (T, T) -> 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
    }
}

As with indexOfObject:inSortedRange:options:usingComparator: it is assumed that the array is sorted with respect to the comparator. It returns either (any) index of the element if the element is already present in the array, or the index where it can be inserted while preserving the order. This corresponds to the NSBinarySearchingInsertionIndex of the NSArray method.

Usage:

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

这篇关于我要如何插入在正确的位置处的元素到斯威夫特一个排序的数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆