37

I'm having difficulty to understand the logic behind the method to find the second highest number in array. The method used is to find the highest in the array but less than the previous highest (which has already been found). The thing that I still can't figure it out is why || highest_score == second_highest is necessary. For example I input three numbers: 98, 56, 3. Without it, both highest and second highest would be 98. Please explain.

int second highest = score[0];  
if (score[i] > second_highest && score[i] < highest_score || highest_score == second_highest)   
    second_highest = score[i];
Tejaskumar
  • 754
  • 8
  • 24
Richard Jackson
  • 371
  • 1
  • 3
  • 3

45 Answers45

41

I'm not convinced that doing what you did fixes the problem; I think it masks yet another problem in your logic. To find the second highest is actually quite simple:

 static int secondHighest(int... nums) {
    int high1 = Integer.MIN_VALUE;
    int high2 = Integer.MIN_VALUE;
    for (int num : nums) {
      if (num > high1) {
        high2 = high1;
        high1 = num;
      } else if (num > high2) {
        high2 = num;
      }
    }
    return high2;
 }

This is O(N) in one pass. If you want to accept ties, then change to if (num >= high1), but as it is, it will return Integer.MIN_VALUE if there aren't at least 2 elements in the array. It will also return Integer.MIN_VALUE if the array contains only the same number.

polygenelubricants
  • 376,812
  • 128
  • 561
  • 623
16
// Initialize these to the smallest value possible
int highest = Integer.MIN_VALUE;
int secondHighest = Integer.MIN_VALUE;

// Loop over the array
for (int i = 0; i < array.Length; i++) {

    // If we've found a new highest number...
    if (array[i] > highest) {

        // ...shift the current highest number to second highest
        secondHighest = highest;

        // ...and set the new highest.
        highest = array[i];
    } else if (array[i] > secondHighest)
        // Just replace the second highest
        secondHighest = array[i];
    }
}

// After exiting the loop, secondHighest now represents the second
// largest value in the array

Edit:

Whoops. Thanks for pointing out my mistake, guys. Fixed now.
Scott Smith
  • 3,900
  • 2
  • 31
  • 63
5

If the first element which second_highest is set to initially is already the highest element, then it should be reassigned to a new element when the next element is found. That is, it's being initialized to 98, and should be set to 56. But, 56 isn't higher than 98, so it won't be set unless you do the check.

If the highest number appears twice, this will result in the second highest value as opposed to the second element that you would find if you sorted the array.

Nathan S.
  • 5,244
  • 3
  • 45
  • 55
  • 1
    +1 for pointing out that this returns the second highest value instead of the element. – Arkku Apr 11 '10 at 02:44
4
let array = [0,12,74,26,82,176,189,8,55,3,189]; 
let highest=0 ;
let secondHighest = 0;
for (let i = 0; i < array.length; i++) { 
if (array[i] > highest) { 
    // ...shift the current highest number to second highest
    secondHighest = highest; 
    // ...and set the new highest.
    highest = array[i]; 
} else if (highest > array[i] > secondHighest) { 
   // Just replace the second highest
   secondHighest = array[i]; 
  }
}
console.log(secondHighest);

enter image description here

Keshav Gera
  • 10,807
  • 1
  • 75
  • 53
  • 7
    Please try to avoid just dumping a code as an answer and try to explain what it does and why. Your code might not be obvious for people who do not have the relevant coding experience. – Frits Jul 06 '16 at 11:42
3

The answers I saw wont work if there are two same largest numbers like the below example.

        int[] randomIntegers = { 1, 5, 4, 2, 8, 1, 8, 9,9 };
        SortedSet<Integer> set = new TreeSet<Integer>();
        for (int i: randomIntegers) {
            set.add(i);
        }
        // Remove the maximum value; print the largest remaining item
        set.remove(set.last());
        System.out.println(set.last());

I have removed it from the Set not from the Array

subhashis
  • 4,629
  • 8
  • 37
  • 52
2

My idea is that you assume that first and second members of the array are your first max and second max. Then you take each new member of an array and compare it with the 2nd max. Don't forget to compare 2nd max with the 1st one. If it's bigger, just swap them.

   public static int getMax22(int[] arr){
    int max1 = arr[0];
    int max2 = arr[1];
    for (int i = 2; i < arr.length; i++){
        if (arr[i] > max2)
        {
            max2 = arr[i];
        }

        if (max2 > max1)
        {
            int temp = max1;
            max1 = max2;
            max2 = temp;
        }
    }
     return max2;
}
Boris
  • 404
  • 1
  • 7
  • 20
1
 public static int secondLargest(int[] input) {
            int largest,secondLargest;

            if(input[0] > input[1]) {
                largest = input[0];
                secondLargest = input[1];
            }
            else {
                largest = input[1];
                secondLargest = input[0];
            }

            for(int i = 2; i < input.length; i++) {
                if((input[i] <= largest) && input[i] > secondLargest) {
                    secondLargest = input[i];
                }

                if(input[i] > largest) {
                    secondLargest = largest;
                    largest = input[i];
                }
            }

            return secondLargest;
        }
Chander Shivdasani
  • 9,878
  • 20
  • 76
  • 107
1

import java.util.Scanner;

public class SecondHighestFromArrayTest {

public static void main(String[] args) {
    Scanner scan = new Scanner(System.in);
    System.out.println("Enter size of Array");
    int size = scan.nextInt();
    int[] arr = new int[size];
    for (int i = 0; i < size; i++) {
        arr[i] = scan.nextInt();
    }
    System.out.println("second highest element " + getSecondHighest(arr));
}

public static int getSecondHighest(int arr[]) {
    int firstHighest = arr[0];
    int secondHighest = arr[0];
    for (int i = 0; i < arr.length; i++) {
        if (arr[i] > firstHighest) {
            secondHighest = firstHighest;
            firstHighest = arr[i];
        } else if (arr[i] > secondHighest) {
            secondHighest = arr[i];
        }
    }
    return secondHighest;
}

}

ngg
  • 1,493
  • 19
  • 14
1

The second largest element in the array : IN Java:

class test2{
    public static void main(String[] args) {

int a[] = {1,2,3,9,5,7,6,4,8};
Arrays.sort(a);
int aa = a[a.length -2 ];
System.out.println(aa);


    }//main

}//end

In Python :

a = [1, 2, 3, 9, 5, 7, 6, 4, 8]

aa = sorted(list(a))
print(aa)
aaa = aa[-2]
print(aaa)
Soudipta Dutta
  • 1,353
  • 1
  • 12
  • 7
0
private static int SecondBiggest(int[] vector)
{
    if (vector == null)
    {
        throw new ArgumentNullException("vector");
    }
    if (vector.Length < 2)
    {
        return int.MinValue;
    }

    int max1 = vector[0];
    int max2 = vector[1];
    for (int i = 2; i < vector.Length; ++i)
    {
        if (max1 > max2 && max1 != vector[i])
        {
            max2 = Math.Max(max2, vector[i]);
        }
        else if (max2 != vector[i])
        {
            max1 = Math.Max(max1, vector[i]);
        }
    }
    return Math.Min(max1, max2);
}

This treats duplicates as the same number. You can change the condition checks if you want to all the biggest and the second biggest to be duplicates.

Pang
  • 9,564
  • 146
  • 81
  • 122
csaam
  • 1,349
  • 9
  • 9
0

If time complexity is not an issue, then You can run bubble sort and within two iterations, you will get your second highest number because in the first iteration of the loop, the largest number will be moved to the last. In the second iteration, the second largest number will be moved next to last.

Stranger
  • 864
  • 4
  • 21
  • 48
0

If you want to 2nd highest and highest number index in array then....

public class Scoller_student {

    public static void main(String[] args) {
        System.out.println("\t\t\tEnter No. of Student\n");
        Scanner scan = new Scanner(System.in);
        int student_no = scan.nextInt();

        // Marks Array.........
        int[] marks;
        marks = new int[student_no];

        // Student name array.....
        String[] names;
        names = new String[student_no];
        int max = 0;
        int sec = max;
        for (int i = 0; i < student_no; i++) {
            System.out.println("\t\t\tEnter Student Name of id = " + i + ".");

            names[i] = scan.next();
            System.out.println("\t\t\tEnter Student Score of id = " + i + ".\n");

            marks[i] = scan.nextInt();
            if (marks[max] < marks[i]) {
                sec = max;
                max = i;
            } else if (marks[sec] < marks[i] && marks[max] != marks[i]) {
                sec = i;
            }
        }

        if (max == sec) {
            sec = 1;
            for (int i = 1; i < student_no; i++) {
                if (marks[sec] < marks[i]) {
                    sec = i;
                }
            }
        }

        System.out.println("\t\t\tHigherst score id = \"" + max + "\" Name : \""
            + names[max] + "\" Max mark : \"" + marks[max] + "\".\n");
        System.out.println("\t\t\tSecond Higherst score id = \"" + sec + "\" Name : \""
            + names[sec] + "\" Max mark : \"" + marks[sec] + "\".\n");

    }
}
Juliano Alves
  • 2,006
  • 4
  • 35
  • 37
0
public class SecondHighest {

    public static void main(String[] args) {
        // TODO Auto-generated method stub

        /*
         * Find the second largest int item in an unsorted array.
         * This solution assumes we have atleast two elements in the array
         * SOLVED! - Order N. 
         * Other possible solution is to solve with Array.sort and get n-2 element.
         * However, Big(O) time NlgN 
         */

        int[] nums = new int[]{1,2,4,3,5,8,55,76,90,34,91};
        int highest,cur, secondHighest = -1;

        int arrayLength = nums.length;
        highest = nums[1] > nums[0] ? nums[1] : nums[0];
        secondHighest = nums[1] < nums[0] ? nums[1] : nums[0];

        if (arrayLength == 2) {
            System.out.println(secondHighest);

        } else {

            for (int x = 0; x < nums.length; x++) {

                cur = nums[x];
                int tmp;

                if (cur < highest && cur > secondHighest)
                    secondHighest = cur;

                else if (cur > secondHighest && cur > highest) {
                    tmp = highest;
                    highest = cur;
                    secondHighest = tmp;
                }

            }   

            System.out.println(secondHighest);

        }   
    }
}
dur
  • 15,689
  • 25
  • 79
  • 125
user2296600
  • 195
  • 2
  • 9
0
public class secondLargestElement 
{
    public static void main(String[] args) 
    {
        int []a1={1,0};
        secondHigh(a1);
    }

    public static void secondHigh(int[] arr)
    {
        try
        {
            int highest,sec_high;
            highest=arr[0];
            sec_high=arr[1];

                for(int i=1;i<arr.length;i++)
                {
                    if(arr[i]>highest)
                    {           
                        sec_high=highest;
                        highest=arr[i]; 
                    }
                    else 
                    // The first condition before the || is to make sure that second highest is not actually same as the highest , think 
                        // about {5,4,5}, you don't want the last  5 to be reported as the sec_high
                        // The other half after || says if the first two elements are same then also replace the sec_high with incoming integer
                        // Think about {5,5,4}
                    if(arr[i]>sec_high && arr[i]<highest || highest==sec_high)
                        sec_high=arr[i];
                }
            //System.out.println("high="+highest +"sec"+sec_high);
            if(highest==sec_high)
                System.out.println("All the elements in the input array are same");
             else
                 System.out.println("The second highest element in the array is:"+ sec_high);

         }

        catch(ArrayIndexOutOfBoundsException e)
        {
        System.out.println("Not enough elements in the array");
        //e.printStackTrace();
        }
    }
}
Deep
  • 528
  • 3
  • 12
  • 27
0

You can find Largest and Third largest number of unsorted array as well.

 public class ThirdLargestNumber {
        public static void main(String[] args) {
            int arr[] = { 220, 200, 100, 100, 300, 600, 50, 5000, 125, 785 };
            int first = 0, second = 0, third = 0, firstTemp = 0, secondTemp = 0;
            for (int i = 0; i <= 9 /*
                                     * Length of array-1. You can use here length
                                     * property of java array instead of hard coded
                                     * value
                                     */; i++) {
                if (arr[i] == first) {
                    continue;
                }
                if (arr[i] > first) {
                    firstTemp = first;
                    secondTemp = second;
                    first = arr[i];
                    second = firstTemp;
                    if (secondTemp > third) {
                        third = secondTemp;
                    }
                } else {
                    if ((arr[i] == second) || (arr[i]) == first) {
                        continue;
                    }
                    if ((arr[i] > second) && (arr[i]) < first) {
                        secondTemp = second;
                        second = arr[i];
                        if (secondTemp > third) {
                            third = secondTemp;
                        }
                    } else {
                        if (arr[i] > third) {
                            third = arr[i];
                        }
                    }
                }
            }
            // System.out.println("Third largest number: " + third);
            System.out.println("Second largest number: " + second);
            // System.out.println("Largest number: " + first);
        }
    }
PVH
  • 788
  • 1
  • 7
  • 12
0

I think for finding the second Highest no we require these lines,if we can use inbuilt function

int[] randomIntegers = {1, 5, 4, 2, 8, 1, 1, 6, 7, 8, 9};
    Arrays.sort(randomIntegers);
    System.out.println(randomIntegers[randomIntegers.length-2]);
0

I am giving solution that's not in JAVA program (written in JavaScript), but it takes o(n/2) iteration to find the highest and second highest number.
Working fiddler link Fiddler link

 var num=[1020215,2000,35,2,54546,456,2,2345,24,545,132,5469,25653,0,2315648978523];
var j=num.length-1;
var firstHighest=0,seoncdHighest=0;
num[0] >num[num.length-1]?(firstHighest=num[0],seoncdHighest=num[num.length-1]):(firstHighest=num[num.length-1],   seoncdHighest=num[0]);
j--;
for(var i=1;i<=num.length/2;i++,j--)
{
   if(num[i] < num[j] )
   {
          if(firstHighest < num[j]){
          seoncdHighest=firstHighest;
           firstHighest= num[j];
          }
           else if(seoncdHighest < num[j] ) {
               seoncdHighest= num[j];

           }
   }
   else {
       if(firstHighest < num[i])
       {
           seoncdHighest=firstHighest;
           firstHighest= num[i];

       }
       else if(seoncdHighest < num[i] ) {
            seoncdHighest= num[i];

       }
   }

}         
Praveen M P
  • 11,314
  • 7
  • 34
  • 41
0
public class SecondandThirdHighestElement {
    public static void main(String[] args) {
        int[] arr = {1,1,2,3,8,1,2,3,3,3,2,3,101,6,6,7,8,8,1001,99,1,0};
        // create three temp variable and store arr of first element in that temp variable so that it will compare with other element
        int firsttemp = arr[0];
        int secondtemp = arr[0];
        int thirdtemp = arr[0];
        //check and find first highest value from array by comparing with other elements if found than save in the first temp variable 
        for (int i = 0; i < arr.length; i++) {
            if(firsttemp <arr[i]){
                firsttemp =  arr[i];
            }//if

        }//for
        //check and find the second highest variable by comparing with other elements in an array and find the element and that element should be smaller than first element array
        for (int i = 0; i < arr.length; i++) {
            if(secondtemp < arr[i] && firsttemp>arr[i]){
                secondtemp = arr[i];
            }//if
        }//for
        //check and find the third highest variable by comparing with other elements in an array and find the element and that element should be smaller than second element array

        for (int i = 0; i < arr.length; i++) {
            if(thirdtemp < arr[i] && secondtemp>arr[i]){
                thirdtemp = arr[i];
            }//if
        }//for

        System.out.println("First Highest Value:"+firsttemp);
        System.out.println("Second Highest Value:"+secondtemp);
        System.out.println("Third Highest  Value:"+thirdtemp);

    }//main
}//class
0

If this question is from the interviewer then please DONT USE SORTING Technique or Don't use any built in methods like Arrays.sort or Collection.sort. The purpose of this questions is how optimal your solution is in terms of performance so the best option would be just implement with your own logic with O(n-1) implementation. The below code is strictly for beginners and not for experienced guys.

  public void printLargest(){


    int num[] ={ 900,90,6,7,5000,4,60000,20,3};

    int largest = num[0];

    int secondLargest = num[1];

    for (int i=1; i<num.length; i++)
    {
        if(largest < num[i])
        {
            secondLargest = largest;
            largest = num[i];


        }
        else if(secondLargest < num[i]){
            secondLargest = num[i];
        }
    }
    System.out.println("Largest : " +largest);
    System.out.println("Second Largest : "+secondLargest);
}
0

Second Largest in O(n/2)

public class SecMaxNum {

    // second Largest number with O(n/2)
    /**
     * @author Rohan Kamat
     * @Date Feb 04, 2016
     */
    public static void main(String[] args) {
        int[] input = { 1, 5, 10, 11, 11, 4, 2, 8, 1, 8, 9, 8 };
        int large = 0, second = 0;

        for (int i = 0; i < input.length - 1; i = i + 2) {
            // System.out.println(i);
            int fist = input[i];
            int sec = input[i + 1];
            if (sec >= fist) {
                int temp = fist;
                fist = sec;
                sec = temp;
            }
            if (fist >= second) {
                if (fist >= large) {
                    large = fist;
                } else {
                    second = fist;
                }

            }

            if (sec >= second) {
                if (sec >= large) {
                    large = sec;
                } else {
                    second = sec;
                }
            }
        }
    }
}
dur
  • 15,689
  • 25
  • 79
  • 125
rohan kamat
  • 583
  • 5
  • 12
  • 1
    Hi, your solution is **not O(n/2)**, because the times of comparison determines the compute complexity for this question. Even if you times of iteration is n/2, but every iteration you would compare more than 2 times so that the whole times of comparison is still more than n times. BTW, when we talk about compute complexity, we usually ignore the coefficient, O(0.5n), O(2n), and O(4n), all of them can be seen as the same class. – very hit Sep 14 '16 at 13:54
0

Problem: The problem is to get the second largest array element.

Observation: Second largest number is defined as the number that has the minimum difference when subtracted from the maximum element in the array.

Solution: This is a two pass solution. First pass is to find the maximum number. Second pass is to find the element that has minimum difference with the maximum element as compared to other array elements. Example: In the array [2, 3, 6, 6, 5] maximum = 6 and second maximum = 5 , since it has the minimum difference to the maximum element 6 - 5 = 1 the solution for second largest = 5

function printSecondMax(myArray) {
  var x, max = myArray[0];
  // Find maximum element 
  for(x in myArray){
     if(max < myArray[x]){
        max = myArray[x];
     }
  }
  var secondMax = myArray[0], diff = max - secondMax;
  // Find second max, an element that has min diff with the max
  for(x in myArray){
    if(diff != 0 && (max - myArray[x]) != 0 && diff > (max - myArray[x])){
        secondMax = myArray[x];
        diff = max - secondMax;
    }
  }
  console.log(secondMax);
}

Complexity : O(n), This is the simplest way to do this.

For finding maximum element even more efficiently one can look into max heap, a call to max-heapify will take O(log n) time to find the max and then pop-ing the top element gives maximum. To get the second maximum, max-heapify after pop-ing the top and keep pop-ing till you get a number that is less than maximum. That will be the second maximum. This solution has O(n log n) complexity.

0

Please try this one: Using this method, You can fined second largest number in array even array contain random number. The first loop is used to solve the problem if largest number come first index of array.

public class secondLargestnum {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        int[] array = new int[6];
        array[0] = 10;
        array[1] = 80;
        array[2] = 5;
        array[3] = 6;
        array[4] = 50;
        array[5] = 60;
        int tem = 0;
        for (int i = 0; i < array.length; i++) {
            if (array[0]>array[i]) {
                tem = array[0];
            array[0] = array[array.length-1];
            array[array.length-1] = tem;
            }
        }
        Integer largest = array[0];
        Integer second_largest = array[0];

        for (int i = 0; i < array.length; i++) {

            if (largest<array[i]) {
                second_large = largest;
                largest = array[i];
            }
            else if (second_large<array[i]) {
                second_large = array[i];

            }

        }
System.out.println("largest number "+largest+" and second largest number "+second_largest);

    }

}
  • 2
    Please [edit] with more information. Code-only and "try this" answers are [discouraged](//meta.stackexchange.com/questions/196187), because they contain no searchable content, and don't explain why someone should "try this". We make an effort here to be a resource for knowledge. – Mogsdad Mar 02 '16 at 16:48
0

public class SecondHighInIntArray {

public static void main(String[] args) {
    int[] intArray=new int[]{2,2,1};
            //{2,2,1,12,3,7,9,-1,-5,7};
    int secHigh=findSecHigh(intArray);
    System.out.println(secHigh);
}

private static int findSecHigh(int[] intArray) {

    int highest=Integer.MIN_VALUE;
    int sechighest=Integer.MIN_VALUE;
    int len=intArray.length;
    for(int i=0;i<len;i++)
    {
        if(intArray[i]>highest)
        {
            sechighest=highest;
            highest=intArray[i];
            continue;
        }

        if(intArray[i]<highest && intArray[i]>sechighest)
        {
            sechighest=intArray[i];
            continue;
        }


    }
    return sechighest;
}

}

SanA
  • 119
  • 1
  • 6
0

Use following function
`

public static int secHigh(int arr[]){
            int firstHigh = 0,secHigh = 0;
            for(int x: arr){
                if(x > firstHigh){
                    secHigh = firstHigh;
                    firstHigh = x;
                }else if(x > secHigh){
                    secHigh = x;
                }
            }
            return secHigh;
        }

Function Call

int secondHigh = secHigh(arr);
devasghar
  • 61
  • 3
0
import java.util.Scanner;

public class SecondLargest {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter size of array : ");
        int n = sc.nextInt();
        int ar[] = new int[n];
        for(int i=0;i<n;i++)
        {
            System.out.print("Enter value for array : ");
            ar[i] = sc.nextInt();
        }
        int m=ar[0],m2=ar[0];
        for(int i=0;i<n;i++)
        {
            if(ar[i]>m)
                m=ar[i];
        }
        for(int i=0;i<n;i++)
        {
            if(ar[i]>m2 && ar[i]<m)
                m2=ar[i];
        }
        System.out.println("Second largest : "+m2);
        sc.close();
    }
}
Keith OYS
  • 2,285
  • 5
  • 32
  • 38
Asish
  • 1
  • 2
0
public void findMax(int a[]) {
    int large = Integer.MIN_VALUE;
    int secondLarge = Integer.MIN_VALUE;
    for (int i = 0; i < a.length; i++) {
        if (large < a[i]) {
            secondLarge = large;
            large = a[i];
        } else if (a[i] > secondLarge) {
            if (a[i] != large) {
                secondLarge = a[i];
            }
        }
    }
    System.out.println("Large number " + large + " Second Large  number " + secondLarge);
}

The above code has been tested with integer arrays having duplicate entries, negative values. Largest number and second largest number are retrived in one pass. This code only fails if array only contains multiple copy of same number like {8,8,8,8} or having only one number.

0
public class SecondLargestNumber
{
  public static void main(String[] args)
  {
    int[] var={-11,-11,-11,-11,115,-11,-9};
    int largest = 0;
    int secLargest = 0;
    if(var.length == 1)
    {
      largest = var[0];
      secLargest = var[0];
    }
    else if(var.length > 1)
    {
      largest= var[0];
      secLargest = var[1];
      for(int i=1;i<var.length;i++)
      {
        if(secLargest!=largest)
        {
          if(var[i]>largest)
          { 
            secLargest = largest;
            largest = var[i];
          }
          else if(var[i]>secLargest && var[i] != largest)
          {
            secLargest= var[i];
          }
        }
        else
        {
          if(var[i]>largest)
          {
           secLargest = largest;
           largest = var[i];
          }
          else
          {
           secLargest = var[i];
          }
       }
    }
  }

    System.out.println("Largest: "+largest+" Second Largest: "+secLargest);
  }
}
  • 1
    It may help if you explain your answer some. What was the problem with the OP's code? How does this fix it? – Gary99 Jun 16 '17 at 13:30
0
   /* Function to print the second largest elements */
    void print2largest(int arr[], int arr_size)
    {
   int i, first, second;

   /* There should be atleast two elements */
   if (arr_size < 2)
   {
    printf(" Invalid Input ");
    return;
    }

   first = second = INT_MIN;
   for (i = 0; i < arr_size ; i ++)
   {
    /* If current element is smaller than first
       then update both first and second */
    if (arr[i] > first)
    {
        second = first;
        first = arr[i];
    }

    /* If arr[i] is in between first and 
       second then update second  */
    else if (arr[i] > second && arr[i] != first)
        second = arr[i];
   }
   if (second == INT_MIN)
    printf("There is no second largest elementn");
    else
    printf("The second largest element is %dn", second);
    }
Venkata
  • 9
  • 1
  • 1
  • 4
0

I have got the simplest logic to find the second largest number may be, it's not. The logic find sum of two number in the array which has the highest value and then check which is greater among two simple............

int ar[]={611,4,556,107,5,55,811};
int sum=ar[0]+ar[1];
int temp=0;
int m=ar[0];
int n=ar[1];
for(int i=0;i<ar.length;i++){
    for(int j=i;j<ar.length;j++){
        if(i!=j){
        temp=ar[i]+ar[j];
        if(temp>sum){
            sum=temp;
            m=ar[i];
            n=ar[j];
        }
        temp=0;

    }
    }
}
if(m>n){
    System.out.println(n);

}
else{
    System.out.println(m);
}
RKP
  • 49
  • 6
0

The simplest way is -

public class SecondLargest {
    public static void main(String[] args) {
        int[] arr = { 1, 2, 5, 6, 3 };

        int first = Integer.MIN_VALUE;
        int second = Integer.MIN_VALUE;
        for (int i = 0; i < arr.length; i++) {
            // If current element is smaller than first then update both first
            // and second
            if (arr[i] > first) {
                second = first;
                first = arr[i];
            }
            // If arr[i] is in between first and second then update second
            else if (arr[i] > second && arr[i] != first) {
                second = arr[i];
            }
        }
    }
}
Avinash Kadam
  • 486
  • 7
  • 10
0

This java program help to find second highest number in any given array. First we have to get highest value and then we have to go second one.

class Demo{
    public static void main(String args[]){
        int arr[]={321,321,321,43,65,234,56,-1,4,45,-67};
        int max=arr[0];
        int len=arr.length;
        for(int i=0;i<len;i++){
            if(max<arr[i]){
                max=arr[i];
            }
        }

        System.out.println("Max value is "+max);

        int secMax=arr[0];
        for(int j=0;j<len;j++){
            if(max>arr[j]){
                if(secMax<arr[j]){
                    secMax=arr[j];
                }
                else if(secMax>arr[j]){
                    secMax=arr[j];
                }

            }
            else if(max==arr[j]){
                //
            }

        }
                System.out.println("Sec Max value is "+secMax);

    }
}
Manjitha Teshara
  • 562
  • 2
  • 8
  • 21
  • 1
    While this code may solve the question, [including an explanation](//meta.stackexchange.com/q/114762) of how and why this solves the problem would really help to improve the quality of your post, and probably result in more up-votes. Remember that you are answering the question for readers in the future, not just the person asking now. Please [edit] your answer to add explanations and give an indication of what limitations and assumptions apply. – Suraj Rao Jun 13 '19 at 12:48
0
 private static void returnSecondHighetsNumber(int[] a) {
         int firstHighest=0;
         int secondHighest=0;
         if(a[0]>=a[1]) {
             firstHighest=a[0];
             secondHighest=a[1];
         }else {
             firstHighest=a[1];
             secondHighest=a[0];
         }
         for (int i = 2; i < a.length; i++) {
             if(a[i] >=firstHighest) {
                 secondHighest=firstHighest;
                 firstHighest=a[i];
             }
             else if(a[i]>=secondHighest) {
                 secondHighest=a[i];
             }
         }
         System.out.println(firstHighest+"---"+secondHighest);
    }
Hirein
  • 135
  • 5
  • 20
0

the idea is to take two variables firstmax fm and secondmax sm and traverse the array.

def print2largest(self,A,N): 
        #code here
    if all(A[x]==A[x-1] for x in range(1,N)): 
        return -1
    sm=0
    fs=0
    for i in range(N):
        if A[i]>fs: 
            sm=fs
            fs=A[i]
        elif A[i]>sm and A[i]!=fs: 
            sm=A[i]
    return sm
    
    
0

I'm not sure how good answers present here. I have below code which is shorter and works good.

static int getSecondHigh(int [] x) {

    int max1st = Integer.MIN_VALUE;
    int max2nd = Integer.MIN_VALUE;
    for (int i = 0; i < x.length; i++) {
        if(max2nd<x[i]){
            if(max1st<x[i]){
                max1st=x[i];
            }else{
                max2nd=x[i];
            }
        }
    }
    return max2nd;
}
0

If you want the strictly second highest number then the following code will work.

This is an extension of most of the answers above. It handles the scenario where both highest and second_highest are same. In that case, if you encounter a number smaller than highest/second_highest, then update second_highest.

If you draw a number line and put two points corresponding to highest and second_highest then it will greatly help understanding the logic.

def second(data):
    highest = max(data[0], data[1])
    second_highest = min(data[0], data[1])
    for i in range(2, len(data)):
        if data[i] > highest:
            second_highest = highest
            highest = data[i]
        elif data[i] > second_highest and data[i] < highest:
            second_highest = data[i]
        elif data[i] < second_highest and highest == second_highest:
            second_highest = data[i]
    return None if highest == second_highest else second_highest
0

This code is for those who don't want to use loop

The Easiest way to find the highest number in the array is

int a[] = {1,2,3,9,5,7,6,4,8};
Arrays.sort(a);
System.out.println(a[1-1]);

The Easiest way to find the second-highest number in the array is

int a[] = {1,2,3,9,5,7,6,4,8};
Arrays.sort(a);
System.out.println(a[2-1]);

The Easiest way to find the third-highest number in the array is

int a[] = {1,2,3,9,5,7,6,4,8};
Arrays.sort(a);
System.out.println(a[3-1]);

The Easiest way to find the fourth-highest number in the array is

int a[] = {1,2,3,9,5,7,6,4,8};
Arrays.sort(a);
System.out.println(a[4-1]);
Abubakar Khalid
  • 109
  • 2
  • 5
0
public class Main
{
    public static int getLargetstNNumbereFromList(int numbers[]){
            int largest = Integer.MIN_VALUE;
        for(int i=0; i<numbers.length; i++){
            if(largest < numbers[i]){
                largest = numbers[i];
            }
        }
        return largest;
    }
    public static void main(String[] args) {
        int numbers[] = {2,13,67,22,21};
        System.out.println(getLargetstNNumbereFromList(numbers));
    }
}
Vinay Pandey
  • 113
  • 5
-1

Its very easy to get the 2nd highest element in an array. I've shows below for all your reference. Hope this will be helpful.

import java.util.Arrays;

public class Testdemo {
    public static void main(String[] args) {
    int[] numbers = {1, 5, 4, 2, 8, 1, 1, 6, 7, 8, 9};
    Arrays.sort(numbers);
    System.out.println("The second Higest Element :" + numbers[numbers.length-2]);
    }
}

Ans - The second Higest Element :8

PAA
  • 1
  • 46
  • 174
  • 282
  • Whenever you're finding 1st , 2nd or 3rd highest and so on, you always needs to be sort an array into an ascending order. – PAA Dec 20 '13 at 12:57
-1
public static void main(String[] args) {

    int[] arr = {0,12,74,56,2,63,45};
    int f1 = 1, f2 = 0, temp = 0;
    int num = 0;

    for (int i = 0; i < arr.length; i++){
        num = arr[i];
        if (f1 < num) {
            temp = f1;
            f1 = num;
            num = temp;
        }
        if (f2 < num) {
            temp = f2;
            f2 = num;
            num = temp;
        }
    }
    System.out.println("First Highest " + f1 + " Second Highest " + f2 + " Third " + num);

}
dur
  • 15,689
  • 25
  • 79
  • 125
-1

I will propose even shorter and simplest answer to the problem and it contains 2 lines of code in the method (import java.util.Arrays is required):

    public static int secMax(int[] num){
    Arrays.sort(num);
    temp = num[num.length-2];

    return temp;
}
TLama
  • 75,147
  • 17
  • 214
  • 392
Georgi Koemdzhiev
  • 11,421
  • 18
  • 62
  • 126
-1
static int secondLargest(int[] input){
    int largest , secondlargest;

    if(input[0]>input[1])
    {
        largest=input[0];
        secondlargest = input[1];
    }
    else
    {
        secondlargest = input[0];
        largest =input[1];
    }
    for(int i =2 ;i<input.length;i++){
        if(input[i]>largest)
        {
            secondlargest  = largest;
            largest = input[i];
        }
        else if(input[i]>secondlargest){
            secondlargest = input[i];
        }

    }
    return secondlargest;
}
Artjom B.
  • 61,146
  • 24
  • 125
  • 222
priyank
  • 99
  • 1
  • 4
-1

Find the second largest number:

public class SecondMaxNumbers {

    public void printTwoMaxNumbers(int[] nums){
        int maxOne = 0;
        int maxTwo = 0;
        for(int n:nums){
            if(maxOne < n){
                maxTwo = maxOne;
                maxOne =n;
            } else if(maxTwo < n){
                maxTwo = n;
            }
        }
        System.out.println("Second Max Number: "+maxTwo);
    }

    public static void main(String a[]){
        int num[] = {10,20,30,40,50,60,70};
        SecondMaxNumbers sec = new SecondMaxNumbers();
        tmn.printTwoMaxNumbers(num);
    }
}
dur
  • 15,689
  • 25
  • 79
  • 125
Sarojini2064130
  • 221
  • 3
  • 7
-2
Scanner sc = new Scanner(System.in);

System.out.println("\n number of input sets::");
int value=sc.nextInt();
System.out.println("\n input sets::");
int[] inputset; 

inputset = new int[value];
for(int i=0;i<value;i++)
{
    inputset[i]=sc.nextInt();
}
int maxvalue=inputset[0];
int secondval=inputset[0];
for(int i=1;i<value;i++)
{
    if(inputset[i]>maxvalue)
   {
        maxvalue=inputset[i];
    }
}
for(int i=1;i<value;i++)
{
    if(inputset[i]>secondval && inputset[i]<maxvalue)
    {
        secondval=inputset[i];
    }
}
System.out.println("\n maxvalue"+ maxvalue);
System.out.println("\n secondmaxvalue"+ secondval);
Joel
  • 7,401
  • 4
  • 52
  • 58
-2
int arr[] = {25, 5, 35, 26, 6, 270, 0};

int large1 = arr[0];
int large2 = arr[1];

for (int i = 2; i < arr.length; i++) {

    if (arr[i] > large1) {

        if (large1 > large2)
            large2 = large1;
        large1 = arr[i];

    } else if (arr[i] > large2)
        large2 = arr[i];                    
}

System.out.println("Large1 " + large1);
System.out.println("Large2 " + large2);
dur
  • 15,689
  • 25
  • 79
  • 125
  • 2
    Instead of only posting some code, even if it answers the question, please don't hesitate to clearly comment what it does / how it works. Thanks – AFract Sep 08 '15 at 12:47
-3

This is my answer in C , O(N) complexity time. Pass the array only once, only three variables. The solution is very intuitive and easy to understand.

 #include <stdio.h>

    int second(int arr[],int size)
    {
        int i, max , secondmax;

        if (arr[0] > arr[1]){
            max = arr[0];
            secondmax = arr[1];
        } else {
            max = arr[1];
            secondmax = arr[0];
        }
        for (i = 2; i < size; i++)
        {
            if ((arr[i] < max) && (arr[i] < secondmax)) {
                continue;
            }
            if ((arr[i] < max) && (arr[i] > secondmax)) {
                secondmax = arr[i];
                continue;
            }
            if ((arr[i] > max)) {
                secondmax = max;
                max = arr[i];
                continue;
            }
        }
        return secondmax;
    }
    void main()
    {
        int arr[] = { 1,10,5,7};
        int size = sizeof(arr) / sizeof(arr[0]);
        int secondmax = second(arr,size);
        printf("%d \n\n", secondmax);
    }
SBusidan
  • 1
  • 1