Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,955 questions

51,897 answers

573 users

How to get the second largest value in array with Java

2 Answers

0 votes
public class MyClass {
    public static void main(String args[]) {
        int array[] = {5, 3, 7, 9, 6, 4};
        int size = array.length;

        for (int i = 0; i < size; i++) {
            for (int j = i + 1; j < size; j++) {
                if (array[i] > array[j]) {
                   int temp = array[i];
                   array[i] = array[j];
                   array[j] = temp;
                }
         }
      }
      System.out.println(array[size - 2]);
    }
}



/*
run:

7

*/

 



answered Mar 21, 2021 by avibootz
0 votes
public class MyClass {
    public static void main(String args[]) {
        int arr[] = {3, 4, 9, 6, 7, 1, 2, 5};
        int len = arr.length;
        int max, secondlargest;
        
        max = secondlargest = Integer.MIN_VALUE;
 
        for (int i = 0; i < len; i++) {
            if(arr[i] > max) {
                secondlargest = max;
                max = arr[i];
            }
            else if(arr[i] > secondlargest && arr[i] < max) {
                secondlargest = arr[i];
            }
        }
        System.out.println(secondlargest);
    }
}



/*
run:

7

*/

 



answered Mar 21, 2021 by avibootz

Related questions

2 answers 73 views
2 answers 205 views
1 answer 101 views
1 answer 111 views
1 answer 113 views
1 answer 117 views
...