【问题标题】:Binary search: error in passing array二分查找:传递数组时出错
【发布时间】:2017-06-29 17:49:49
【问题描述】:

我有一个名为array 的对象数组,它的类型是votes。在数组的对象中有一个名为nameSubject 的字段,它是一个字符串。 如何传递我的数组和我想与主题名称进行比较的字符串?这是我的功能:

static func binarySearch(inputArr: [votes], searchItem: String)->Int?{
    var lowerIndex = 0;
    var upperIndex = inputArr.count - 1

    while (true) {
        var currentIndex = (lowerIndex + upperIndex)/2
        if(inputArr[currentIndex] == searchItem) {
            return currentIndex
        } else if (lowerIndex > upperIndex) {
            return nil
        } else {
            if (inputArr[currentIndex] > searchItem) {
                upperIndex = currentIndex - 1
            } else {
                lowerIndex = currentIndex + 1
            }
        }
    }
}

错误出现在第一个和第二个if 中,并表示:二进制运算符'=='不能应用于'votes'和'String'类型的操作数”

【问题讨论】:

  • 你想在第二个 else 语句中做什么?
  • 如果您经常这样做,最好将字典映射 nameSubjectvotes 对象
  • 顺便说一句,Swift 的约定是使用 UpperCamelCase,单数命名类型,例如 Vote

标签: swift xcode


【解决方案1】:

我会这样写:

// Precondition: the array is sorted by ascending elements
extension Array where Element: Comparable {
    func binarySearchForIndex(of desiredElement: Element) -> Int? {
        return binarySearchForIndex(of: desiredElement, by: {$0})
    }
}

// Precondition: the array is sorted by ascending values of the picker closure.
extension Array {
    func binarySearchForIndex<T>(
        of desiredElement: T,
        by picker: (Element) -> T
    ) -> Int?
    where T: Comparable {
        var lowerIndex = 0;
        var upperIndex = self.count - 1

        while (true) {
            let currentIndex = (lowerIndex + upperIndex)/2
            let item = picker(self[currentIndex])

            if item == desiredElement { return currentIndex }
            else if lowerIndex > upperIndex { return nil }
            else {
                if (item > desiredElement) {
                    upperIndex = currentIndex - 1
                } else {
                    lowerIndex = currentIndex + 1
                }
            }
        }
    }
}

第一个扩展允许您直接对 Array 中的任何 Array 项进行二分搜索。

第二个扩展允许您对任何Array 项进行二进制搜索,提供一个闭包来指定您要搜索的元素的哪些属性。你可以这样做:

let indexOfBobsVote = votes
    .sorted{ $0.nameSubject < $0.nameSubject}
    .binarySearchForIndex(of: "bob", by: { $0.nameSubject })

【讨论】:

    【解决方案2】:

    您应该将该字符串与对象的 nameSubject 字符串进行比较,而不是对象本身。

    所以你应该做的比较是:

    inputArr[currentIndex].nameSubject == searchItem
    

    尽管这对您之后进行的比较没有帮助。我不确定您要使用 ">"

    评估什么属性

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-12
      • 2017-08-12
      • 1970-01-01
      • 2020-11-13
      • 2021-04-08
      相关资源
      最近更新 更多