using arrays or arraylist ,how to find highest value in a group of numbers ? [Resolved]

Posted by Nav234 under Interview Questions on 9/9/2010 | Points: 10 | Views : 6609 | Status : [Member] | Replies : 5
Hi all,

can any one explain me using arrays or arraylist & any latest methods like generics ,how to find highest value in a collection
of numbers ?

thanks in advance

S.Naveen...


Responses

Posted by: Peermohamedmydeen on: 9/13/2010 [Member] Bronze | Points: 50

Up
0
Down

Resolved
Hi,

Let us consider an ArrayList called arrScores.

ArrayList arrScores = new ArrayList();


Am adding few numeric items into ArrayList like

arrScores.Add(5);
arrScores.Add(3);
arrScores.Add(7);
arrScores.Add(1);
arrScores.Add(2);
arrScores.Add(4);
arrScores.Add(6);



Now Am having order of the items like 5,3,7,1,2,4,6.

Now call the Sort Method.

arrScores.Sort(); // The array list items will be sorted in ascending order like 1,2,3,4,5,6,7  


Now call the Reverse method.

arrScores.Reverse();  // The array list items will be reversed like 7,6,5,4,3,2,1  


Now get the highest value by giving 0 index in the array list.

int nHighestVal = int.Parse(arrScores[0].ToString());  // The nHighestVal  will be 7.


If you want the least value. Do only sort and get the item by 0th index.










Nav234, if this helps please login to Mark As Answer. | Alert Moderator

Posted by: Peermohamedmydeen on: 9/13/2010 [Member] Bronze | Points: 25

Up
0
Down
Hi,

By using ArrayList, we can perform Sort() and Reverse().

Then we can get the First element. It will be the highest value..

Try this.

Thanks
PMM :)

Nav234, if this helps please login to Mark As Answer. | Alert Moderator

Posted by: Nav234 on: 9/13/2010 [Member] Starter | Points: 25

Up
0
Down
thank you
can you explain with code please

thanks in advance

S.Naveen...

Nav234, if this helps please login to Mark As Answer. | Alert Moderator

Posted by: Nav234 on: 9/13/2010 [Member] Starter | Points: 25

Up
0
Down
Thanks ,

Have a small doubt ,why to call reverse method.I mean after sorting ,the last number would be highest right .

Here after sorting method,

int nHighestVal = int.Parse(arrScores[6].ToString()); // The nHighestVal will be 7.

Does this work ? or any specific reason to use reverse?

thanks in advance


Thanks

S.Naveen...

Nav234, if this helps please login to Mark As Answer. | Alert Moderator

Posted by: Peermohamedmydeen on: 9/13/2010 [Member] Bronze | Points: 25

Up
0
Down
Hi,

We can do either the way as you said.

Instead of hardcode the index, We can do as follows

int nHighestVal = int.Parse(arrScores[arrScores.Count-1].ToString()); // The nHighestVal will be 7.


We can give the item count minus one, to point the last index of the array list.



Nav234, if this helps please login to Mark As Answer. | Alert Moderator

Login to post response