Sunday, May 22, 2016

FIND THE SECOND LARGEST NUMBER IN THE ARRAY

/**
* find the second largest integer in an array.
* @param ia an array of integers
* @return the second largest number in ia
*/
private static int secondLargest(int[] ia)
{
int first_largest=0;
int second_largest=0;

//find the first largest
for (int i=0; i<ia.length; i++){
if (ia[i] > first_largest)//determine first the first largest so that we can identify the second largest
first_largest=ia[i];

}
//find the second largest
for (int i=0; i<ia.length; i++){
if (ia[i] > second_largest && ia[i]<first_largest) //check if it is the second largest
second_largest=ia[i];

}

return second_largest;
} //secondLargest

No comments:

Post a Comment