4
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
    }
}
Marco
  • 1,057
  • 1
  • 19
  • 36
  • 7
    "Better way" in what sense? Finding the minimum must iterate over all elements, therefore I don't think that anything can be faster than your explicit loop. – Martin R Mar 26 '15 at 09:40
  • minElement do a loop to get the min element, find do another loop to get the position of the min element. I was searching for a single loop. – Marco Mar 26 '15 at 09:45
  • I meant your second solution `for (index,value) in enumerate(array) ...` which does a single pass over the array. I assume that is the fastest way. – Martin R Mar 26 '15 at 09:47
  • good, I've understand that's the better way. Thanks. – Marco Mar 26 '15 at 09:49
  • 1
    Actually the answer depends on how large the array is and how the numbers are distributed. Your first solution (minElement + find) can be faster if a minimum is likely to be found "early" in the array (e.g. if you have 10000 numbers in the range 0 .. 9). – Martin R Mar 26 '15 at 10:08
  • Possible duplicate of [Find min / max value in Swift Array](https://stackoverflow.com/questions/24036514/find-min-max-value-in-swift-array) – pkamb Sep 23 '21 at 04:13

2 Answers2

6

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 :)

rintaro
  • 51,423
  • 14
  • 131
  • 139
6

I think you should stick with your original code at the very top. It is very easy to read and understand (very important for future maintenance) and you let the compiler use built-in optimizations.

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

Like Chris Lattner shared in one of the WWDC talks this year, the goal should be for readability and understandability, opposed to either terseness or verbosity. A question that I like to ask myself when deciding which way to go is:

If I read this bit of code a year or two from now, will I immediately grasp what it is doing?

There is nothing more frustrating than looking at your own code and saying "Huh???"

Michael Sheaver
  • 2,059
  • 5
  • 25
  • 38