我是 Swift的新手,也是Apple编程的新手.我写了这段代码来进行二分查找. func binarySearchX:Comparable (needle:X, haystack:[X])-X? { if haystack.isEmpty { return nil } let mid = haystack.count / 2 let found = haystack[mi
func binarySearch<X:Comparable> (needle:X, haystack:[X])->X? {
if haystack.isEmpty { return nil }
let mid = haystack.count / 2
let found = haystack[mid]
if found == needle {
return needle
}
else if found < needle {
return binarySearch(needle, haystack[0..<mid])
}
else {
return binarySearch(needle, haystack[mid+1..<haystack.count])
}
}
我在递归调用上遇到语法错误,因为第二个参数的类型是ArraySlice< X>而不是Array< X>.
我通过使用相同的版本重载binarySearch来解决这个问题,除了第二个参数是ArraySlice< X>类型.
如果它可以在一个函数中完成,我认为它会更优雅.是否有合适的类型统一Array和ArraySlice?我尝试使用ArrayLiteralConvertible< X>但由于某些原因,没有计数成员.我在文档中找到自己的方法仍然有点麻烦,所以我可能很容易忽略一个更好的选择.
你能建议一个好方法吗?如果它涉及使用内置类,你可以给我一个关于如何为自己下次找到它的提示,而不是写给SO吗?
是的,Array / ArraySlice很烦人.您需要的基本通用要求详见 this问题.但是,为了满足您的要求,不幸的是,您必须获得一些非常可怕的功能签名.但是有可能:func bSearch<
S : Sliceable where S.SubSlice : Sliceable,
S.SubSlice.Generator.Element == S.Generator.Element,
S.SubSlice.SubSlice == S.SubSlice,
S.Generator.Element : Comparable,
S.Index : IntegerArithmeticType,
S.Index : IntegerLiteralConvertible,
S.SubSlice.Index == S.Index
>(el: S.Generator.Element, list: S) -> S.Generator.Element? {
if list.isEmpty { return nil }
let midInd = list.endIndex / 2
let midEl: S.Generator.Element = list[midInd] // type inference giving me some bugs here
if midEl == el {
return el
}
return midEl < el ?
bSearch(el, list: list[midInd+1..<list.endIndex]) :
bSearch(el, list: list[0..<midInd])
}
而对于Swift 1.2,只需更换机身:
if isEmpty(list) { return nil }
let midInd = list.endIndex / 2
let midEl: S.Generator.Element = list[midInd] // type inference giving me some bugs here
if midEl == el {
return el
}
return midEl < el ?
bSearch(el, list[midInd+1..<list.endIndex]) :
bSearch(el, list[0..<midInd])
