How to find index of element with minimum value?

I suppose the easiest way is list.indexOf(list.min). It will throw an exception when the list is empty, although so will Daniel's answer.


An empty list has no minimal value. A list of only one element has that element as its minimum. For all other lists the minimum is either the first element of that list or the minimum of the rest of the list, depending on which is greater.

So to find the index this becomes: For a list of length 1 the index of the minimum is 0. If the list has more than one element and the minimum of the tail is greater than the head, it's also 0. If the head is greater then the index is the index of the minimum of the tail plus one.


Starting in Scala 2.13, a slightly safer solution (which handles empty lists) would consist in using minOption/maxOption which returns None if the sequence is empty:

List(34, 11, 98, 56, 43).zipWithIndex.minOption.map(_._2)
// Option[Int] = Some(1)
List[Int]().zipWithIndex.minOption.map(_._2)
// Option[Int] = None

This way you could also decide to fallback on a default value when the list is empty:

List(34, 11, 98, 56, 43).zipWithIndex.minOption.map(_._2).getOrElse(-1)
// Int = 1
List[Int]().zipWithIndex.minOption.map(_._2).getOrElse(-1)
// Int = -1

On Scala 2.8:

List(34, 11, 98, 56, 43).zipWithIndex.min._2