我有一个名为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' 类型的操作数"
最佳答案
我会这样写:
// 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
}
}
}
}
}
第一个扩展允许您直接对 Comparable
项目的任何 Array
进行二进制搜索。
第二个扩展允许您对任何 Array
项进行二分搜索,提供一个闭包来指定您要搜索的元素属性。你可以这样做:
let indexOfBobsVote = votes
.sorted{ $0.nameSubject < $0.nameSubject}
.binarySearchForIndex(of: "bob", by: { $0.nameSubject })
关于swift - 二进制搜索 : error in passing array,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44831883/