tags:

views:

3385

answers:

4

I have the following List<int> collection and I need to find the highest integer in the collection. It could have an arbitrary number of integers and I can have same integer value for multiple times.

List<int> MyList = new List<int> { 3, 4, 6, 7, 9, 3, 4, 5, 5 };

What is the best algorithm to use for finding the highest integer? I am using C# and the .NET 3.5 framework.

+33  A: 

You can just do:

int max = MyList.Max();

See Enumerable.Max for details.

Reed Copsey
make sure you add using System.Linq;as Max is an extension method.
aquinas
+6  A: 

Enumerable has a Max function that will do this.

Looking at the implementation for the integer specific method using Reflector, the method loops through each element in the the IEnumerable source and compares it with what was previously the highest value.

Timothy Carter
+4  A: 

If you need to retrieve the maximum value frequently you might think about creating your own list class (or derive from List) which keeps the maximum item in a cache. Such a class could look like this:

public class MaxList<T> : IList<T>, ICollection<T>, IEnumerable<T>
{
    T Maximum { get; set; }
    List<T> _list;

    public T this[int index] { get; set; }

    public void Add(T item)
    {
        if (item > this.Maximum)
        {
            this.Maximum = item;
        }
        _list.Add(item);
    }

    // ... IEnumerable<T>, ICollection<T> and IList<T> members 

}

Alternatively, you could derive from List directly and overwrite the Add and Remove methods (basically all methods modifying list items) and update the cache accordingly.

If such an approach is really a benefit depends on your scenario. IT definitely is if you have a very large list with is rarely updated and you need to retrieve the maximum frequently. Otherwise go for the solutions already suggested because they are much simpler.

0xA3
You'll need to have a state indicating if the max is currently valid. It should be invalid if an item is removed that is equal to the maximum. In this case, the get method will need to rescan the list (using the Max extension method, probably) for a new maximum. You could also just use a sorted list, but there are other prices associated with that.
Brian
Yes, you are right. I was lazy and only provided a sceleton class where I left out the remove method(s) and indexer where the cache needs to be invalidated. I also left out the method for recalculating the cache which could be using Enumberable.Max.
0xA3
A: 

genericlist.Remove(genericlist.Max)

Jake