retrieve highest value in ArrayList

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

Guest

hello folks,

is there a way to retrieve the highest value in the ArrayList?
let say i have a value in the array: {1, 4, 15, 3, 7}
it should return a value 15 as the result.

i've looked at the Sort Method ( ) but doesn't seem like it can do the job
or am i missing something?
 
Ada said:
hello folks,

is there a way to retrieve the highest value in the ArrayList?
let say i have a value in the array: {1, 4, 15, 3, 7}
it should return a value 15 as the result.

i've looked at the Sort Method ( ) but doesn't seem like it can do the job
or am i missing something?

A Sort method should return a sorted list, so take the first or last
value (depending on sort order) to get the "highest" value.

But I think it would be quicker just to loop (once!) through the list:

public int FindMax(ArrayList myList)
{
int max = Int32.MinValue;
for (i = 0; i<myList.Count; i++)
{
int val = (int)myArrayList;
if (val > max)
max = val;
}
return max;
}
 
Ada said:
hello folks,

is there a way to retrieve the highest value in the ArrayList?
let say i have a value in the array: {1, 4, 15, 3, 7}
it should return a value 15 as the result.

i've looked at the Sort Method ( ) but doesn't seem like it can do the job
or am i missing something?
If you can assume all elements are the same type, int32 for example, you can
write a simple method to return the largest value, something like this
(thrown together with no regard for anything but basic functionality)...

public static int getBiggest(ArrayList bigList)

{

int large = Convert.ToInt32(bigList[0]);

for(int i = 1; i < bigList.Count; i++)

{

int c = Convert.ToInt32(bigList);

if (c > large)

{

large = c;

}

}

return large;

}

Or, you could just call the Sort() method, then pull the last element.
 
hi,

If the array is not sorted you have no other option but to iterate on it.

cheers,
 
thanks guys for the response.

now, the next question.
iterate thru the ARRAY LIST or use the SORT METHOD and pull out the last
element (assuming sorting in ascending order), is there a tool in VS.NET or
3rd party to measure the execution speed or/and efficiency of the code?
 
Ada said:
thanks guys for the response.

now, the next question.
iterate thru the ARRAY LIST or use the SORT METHOD and pull out the last
element (assuming sorting in ascending order), is there a tool in VS.NET or
3rd party to measure the execution speed or/and efficiency of the code?

Iterating would require just one pass through the list.
Even the most efficient sorting method should require more.

You could test this with something like:
- remember DateTime.Now
- execute iteration or sort a lot of times (10.000 or more)
- get a new Datetime.Now
- print the difference between the dates
 
Hi,

IIRC
iterating takes n comparision , sorting require nlogn

so unless you need it sorted for some other reason, just iterate on it.

cheers,
 
Back
Top