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
    }
}
6
  • 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. Commented Mar 26, 2015 at 9: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. Commented Mar 26, 2015 at 9: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. Commented Mar 26, 2015 at 9:47
  • good, I've understand that's the better way. Thanks. Commented Mar 26, 2015 at 9: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). Commented Mar 26, 2015 at 10:08

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

Comments

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???"

1 Comment

Totally agree. This is my preferred solution.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.