Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fast/efficient way to get index of minimum value in List<T>?

Is there any way to find minimum value index more efficient/faster than this?

int minimumValueIndex = List.IndexOf(List.Min());
like image 617
Kamil Avatar asked May 01 '13 17:05

Kamil


1 Answers

Yes, you can remove the overhead of List.IndexOf() by building a custom Min() extension. (Really, Enumerable.Min() should have an extension that selects the original element by key instead of selecting a transformation. This oversight is particularly painful in situations like this.)

public static int IndexOfMin(this IList<int> self)
{
    if (self == null) {
        throw new ArgumentNullException("self");
    }

    if (self.Count == 0) {
        throw new ArgumentException("List is empty.", "self");
    }

    int min = self[0];
    int minIndex = 0;

    for (int i = 1; i < self.Count; ++i) {
        if (self[i] < min) {
            min = self[i];
            minIndex = i;
        }
    }

    return minIndex;
}
like image 185
cdhowie Avatar answered Sep 19 '22 20:09

cdhowie