我写了一个 Swift 算法,用于查找 Swift 数组中的最大值及其索引。这是受 Matlab & Octave 中的“max.m”函数的启发。
这里的专家能否建议一种在速度方面改进该算法的方法?我的意思是它是否可以做得更快,或者您认为这对于大型阵列(有时是 15000 个样本)来说是一种合理的方法。
public func max (y: [Double]) -> (Int, Double) {
let inLen = y.count
var out = Double()
var outp = Int()
if (1 == inLen) { // if only one element
out = y[0]
outp = 0
} else if (0 == inLen) { // if no elements
out = -1
outp = -1
} else {
out = y[0]
outp = 0
for ii in 1...inLen-1 {
if (out<y[ii]){
out = y[ii]
outp = ii
}
}
}
return (outp, out)
}
// Call the function
let y: [Double] = [3, 4, 5, 6, 7, 8, 9, 100, 100, 11, 12, 13, 14, 15, -8, -7, -7, 99]
let (ind, value) = max(y: y)
print(ind) // 7
print(value) // 100.0
最佳答案
您可以使用 vDSP_maxviD)()
来自 Accelerate 框架的功能。 vDSP 函数使用
vDSP_Length
(又名 UInt
)用于数组计数和索引,因此您必须将
索引到 Int
以实现 Swift 互操作性。
import Accelerate
let array: [Double] = ...
var elem = 0.0
var vdspIndex: vDSP_Length = 0
vDSP_maxviD(array, 1, &elem, &vdspIndex, vDSP_Length(array.count))
let idx = Int(vdspIndex)
print("max:", elem, "at index:", idx)
事实证明,这比您的显式快了大约 5 倍 15,000 个元素数组的循环(在以 Release模式编译的 iMac 上)。
关于arrays - Swift数组中最大值及其索引的高效算法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42128950/