我编写了一个 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