Search code examples
javaalgorithmtreemap

How do you find second highest number in an integer array?


How do you find second highest number in an integer array?

Is this a good implementation?

Is there a better way to do this?

public class Find2ndHighest {
    public static void main(String[] args) {
        int b[] = {2,3,1,0,5};

        TreeMap<Integer,Integer> tree = new TreeMap<Integer,Integer>();
        for(int i = 0; i<b.length;i++){
            tree.put(b[i], 0);
        }
        System.out.println(tree.floorKey(tree.lastKey()-1));
    }
}

Solution

  • You can sort the array and fetch second last element which executes in O(nlogn), but this works only if you are sure that there are no duplicates in the array else this method is unreliable.

    You can iterate through the array maintain counters for highest and second highest and return 2nd highest. This executes in O(n)

    Example:

     int highest = Integer.MIN_VALUE+1; 
     int sec_highest = Integer.MIN_VALUE;
     for(int i : b) //b is array of integers
     {
         if(i>highest)
         {
            sec_highest = highest; //make current highest to second highest
            highest = i; //make current value to highest
         }
         else if(i>sec_highest && i != highest) 
         {
            sec_highest = i;
         }
     }
    

    Another solution is:

    int b[] = {1, 2, 31,22,12,12};
    Arrays.sort(b);
    System.out.println(b[b.length-2]);