public class getThirdLargest
{
public static void main(String[] args)
{
int array[] = {8, 2, 5, 7, 1};
System.out.println(getThirdLargest(array));
}
public static int getThirdLargest(int[] array)
{
int firstLargestIndex = 0;
int secondLargestIndex;
int thirdLargestIndex;
if (array.length == 1 || array.length == 2)
{
System.out.println("Not enough numbers.");
return -1;
}
else if (array.length == 3)
{
if (array[0] > array[1])
{
return array[0];
}
else if (array[1] > array[0])
{
return array[1];
}
else
{
return array[2];
}
}
for(int i = 0; i < array.length; i++)
{
if (array[firstLargestIndex] < array[i])
{
firstLargestIndex = i;
}
}
secondLargestIndex = (firstLargestIndex + 1) % array.length;
for(int i = 0; i < array.length; i++ )
{
if (i != firstLargestIndex)
{
if (array[secondLargestIndex] < array[i])
{
secondLargestIndex = i;
}
}
}
thirdLargestIndex = (secondLargestIndex + 1) % array.length;
for(int i = 0; i < array.length; i++ )
{
if (i != firstLargestIndex && i != secondLargestIndex)
{
if (array[thirdLargestIndex] < array[i])
{
thirdLargestIndex = i;
}
}
}
return array[thirdLargestIndex];
}
}