July 16, 2015

Find Second Highest Number From An Array

Let's say we need to find the second highest number from an array without sorting. Also, we need to do this in one iteration.

In this scenario we will use two variables firstHi and secondHi. We will start iterating the array, if the firstHi is less than the value of current element, we will make that element as the first highest.



When the current value is less than firstHi but greater than secondHi, we will set the value of secondHi with the value of current element.



If we are allowed to use the sort method of array, then we can find the second largest value by:

Arrays.sort(a);  
secondHi= a[total-2];

We can also use sort method of Collections:
List < Integer > list=Arrays.asList(a);  
Collections.sort(list);  
secondHi=list.get(total-2);

-K Himaanshu Shuklaa..

No comments:

Post a Comment