C# find highest array value and index
If the index is not sorted, you have to iterate through the array at least once to find the highest value. I'd use a simple for
loop:
int? maxVal = null; //nullable so this works even if you have all super-low negativesint index = -1;for (int i = 0; i < anArray.Length; i++){ int thisNum = anArray[i]; if (!maxVal.HasValue || thisNum > maxVal.Value) { maxVal = thisNum; index = i; }}
This is more verbose than something using LINQ or other one-line solutions, but it's probably a little faster. There's really no way to make this faster than O(N).