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
}
}
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 :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With