javaalgorithmarraylist

Second highest number ArrayList


So I got this code so far:

int secondLargest = list.get(0);
int largest = list.get(0);
for (int i = 0; i < list.size(); i++)
{
    if(list.get(i) > largest)
    {
        secondLargest = largest;
        largest = list.get(i);

        if(list.get(i) > secondLargest && list.get(i) != largest)
        {
            secondLargest = list.get(i);
        }
    }
}

System.out.print("Second biggest number ");
return secondLargest;       

The problem is that when I use this code (the list is:)

list2.add(1);
list2.add(2);
list2.add(10);
list2.add(9);
list2.add(8);
list2.add(7);

the "search" for the second highest number stops at 2, because 10 is the highest number. How do I fix this?


Solution

  • Put the second if condition outside the first if condition.

    Because second largest is smaller than largest so you will never find it in the if block which check for the largest value.

    int secondLargest = (int) list.get(0);
    int largest = list.get(0);
    for (int i = 1; i < list.size(); i++) {
      if(list.get(i) > largest) {
        secondLargest = largest;
        largest = list.get(i);
      }
      if(list.get(i) > secondLargest && list.get(i) != largest) {
        secondLargest = list.get(i);
      }
    }
    System.out.print("Second biggest number ");
    return secondLargest;