问题描述
我写了一种Swift算法,用于在Swift数组中查找最大值及其索引.这是受Matlab&中的"max.m"函数启发的.八度.
I have written an algorithm is Swift for finding the maximum value and its index in a Swift array. This is inspired by the "max.m" function in Matlab & Octave.
这里的专家能否提出一种在速度方面改进此算法的方法?我的意思是说它可以做得更快,或者您认为这对于大型阵列(有时15,000个样本)是一种合理的方法.
Could the experts here suggest a way to improve this algorithm in terms of speed? I mean could it be made faster or you think this is a reasonable approach for large arrays (sometimes 15000 samples).
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
(aka UInt
)来获取数组计数和索引,因此您必须转换Swift互操作性的Int
索引.
You can use the vDSP_maxviD)()
function from the Accelerate framework. The vDSP functions usevDSP_Length
(aka UInt
) for array counts and indices, so you have to convert theindex to an Int
for Swift interoperability.
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个元素的数组(在以发布"模式编译的iMac上).
This turned out to be about a factor 5 faster than your explicitloop for a 15,000 element array (on an iMac compiled in Release mode).
这篇关于Swift数组中的最大值最大值算法及其索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!