Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Efficient algorithm for maximum value and its index in Swift array

Tags:

arrays

swift

max

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.

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 
like image 991
Pat Avatar asked Nov 04 '25 20:11

Pat


1 Answers

You can use the vDSP_maxviD)() function from the Accelerate framework. The vDSP functions use vDSP_Length (aka UInt) for array counts and indices, so you have to convert the index 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)

This turned out to be about a factor 5 faster than your explicit loop for a 15,000 element array (on an iMac compiled in Release mode).

like image 90
Martin R Avatar answered Nov 07 '25 11:11

Martin R



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!