highest value in a an array

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

hey all,
i have an int[] array and was just wondering if there is a way to get the
highest value in the array?

for instance,
int[] myValues = new int[] { 0, 1, 2 }

highest value is 2.

thanks,
rodchar
 
Hi rodchar,

Basically you will need to sort the array and then choose the last element
(assuming you have sorted it in lowest to highest order).

e.g.
int[] integerArray = new int[10]{23,8,34,1,19,263,11,4,2,84};
Array.Sort(integerArray);

The element integerArray[9] will now contain 263 which is the highest value
in the array. There are many ways to sort an array but I think the Static
Sort of the Array class is pretty optimised as it goes.

Hope this helps
wibberlet
Development blog at http://wibberlet.blogspot.com
 
Wibberlet said:
Basically you will need to sort the array and then choose the last element
(assuming you have sorted it in lowest to highest order).

Well, that's one way to do it. Its complexity is O(n log n) however,
whereas just finding the maximal value only needs to be O(n).

You just go through the array, remembering the current highest value:

int max = int.MinValue;

foreach (int value in integerArray)
{
if (value > max)
{
max = value;
}
}

LINQ will make all of this rather easier.
 
Back
Top