How to find second largest number in an array in Java?

后端 未结 10 998
野的像风
野的像风 2021-01-01 05:57

I\'m just practicing some MIT java assignments. But, I\'m not sure how to find the second largest number. http://ocw.csail.mit.edu/f/13

  public class Marath         


        
10条回答
  •  北荒
    北荒 (楼主)
    2021-01-01 06:19

    Find the second largest element in the given array:

    public static void findSecondMax(){
            int[] arr = {3, 2, 20, 4, 1, 9, 6, 3, 8};
    
            int max = 0;
            int secondMax = 0;
    
            for(int i =0; i< arr.length; i++) {
    
                if(max < arr[i]) max = arr[i];
    
                if((max > arr[i]) && (secondMax < arr[i])) secondMax = arr[i];
    
            }
    
            System.out.println(secondMax);
        }
    

提交回复
热议问题