Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fast way to find min in an Array in Swift

Tags:

arrays

swift

let numbers = [1, 6, 3, 9, 4, 6]

let min = minElement(numbers) // 1
let position = find(array, min)!

Is there a better way to find the position of the minor element in an array? A loop search, it's fastest in this case.

min = Int.max
for (index,value) in enumerate(array){
    if value < min{
        min = value
        position = index
    }
}
like image 678
Marco Avatar asked Dec 14 '22 15:12

Marco


1 Answers

If you like "functional" way:

let array = [6, 3, 1, 9, 4, 6]

let (position, min) = reduce(enumerate(array), (-1, Int.max)) {
    $0.1 < $1.1 ? $0 : $1
}

position // -> 2
min // -> 1

But I don't know it's faster than for loop :)

like image 108
rintaro Avatar answered Jan 15 '23 17:01

rintaro