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.

//find the 2nd higest value without sorting
//using one loop
public int findSecondHighestWithOutSort(int a[]) throws Exception {
if (a == null || a.length < 2)
throw new Exception("Invalid Input");
int firstHi = 0, secondHi = 0;
for (int i = 0; i < a.length; i++) {
if (firstHi < a[i])
firstHi = a[i];
else if (firstHi > a[i] && a[i] > secondHi)
secondHi = a[i];
}
return secondHi;
}
public int getSecondLargest(int[] a) {
int temp;
int alength = a.length;
for (int i = 0; i < alength; i++) {
for (int j = i + 1; j < alength; j++) {
if (a[i] > a[j]) {
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
}
return a[alength - 2];
}


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